[英]Quicksort in C++ with std::vector, EXC_BAD_ACCESS code 2
VS Code catches this exception when I run my quicksort algorithm: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffffc).当我运行快速排序算法时,VS Code 会捕获此异常:EXC_BAD_ACCESS(代码=2,地址=0x7ffeef3ffffc)。 This happens on the first line in partition():
这发生在 partition() 的第一行:
int i = p;
I have tried to implement the Cormen algorithm: http://www.cs.fsu.edu/~lacher/courses/COP4531/lectures/sorts/slide09.html我试图实现 Cormen 算法: http : //www.cs.fsu.edu/~lacher/courses/COP4531/lectures/sorts/slide09.html
Why can I not access the variable p?为什么我不能访问变量 p? Is it released, and if so, how do I fix this?
它是否已发布,如果已发布,我该如何解决?
//.h file
void sortVector(vector<int> &vec, int p=0, int r=-2);
int partition(vector<int> &vec, int p, int r);
//.cpp file
int partition(vector<int> &vec, int p, int r) {
int i = p;
for (int j = p; j <r-1; ++j) {
if (vec[j] < vec[r-1]) {
swap(vec[j], vec[r-1]);
i++;
}
swap(vec[i], vec[r-1]);
}
return i;
}
void sortVector(vector<int> &vec, int p, int r) {
if (r == -2) {
r = vec.size();
}
if (p-r<1) {
int q = partition(vec, p, r);
sortVector(vec, p, q);
sortVector(vec, q+1, r);
}
}
I am including "std_lib_facilities.h" from Stroustrup: Programming Principles and Practice Using C++.我包括来自 Stroustrup:Programming Principles and Practice Using C++ 的“std_lib_facilities.h”。
You need to write swap(vec[i], vec[r-1]);
你需要写
swap(vec[i], vec[r-1]);
out of for
loop.出
for
循环。
It should be like this -应该是这样的——
//.cpp file
int partition(vector<int> &vec, int p, int r) {
int i = p;
for (int j = p; j <r-1; ++j) {
if (vec[j] < vec[r-1]) {
swap(vec[j], vec[r-1]);
i++;
}
}
swap(vec[i], vec[r-1]);
return i;
}
There were problems in both functions:两个函数都存在问题:
partition():划分():
if (vec[j] < vec[r-1])
became if (vec[j] <= vec[r-1])
if (vec[j] < vec[r-1])
变成if (vec[j] <= vec[r-1])
sortVector():排序向量():
if (pr<1)
became if (p<r)
if (pr<1)
变成 if (p<r)
Working code below.下面的工作代码。
int partition(vector<int> &vec, int p, int r) {
int i = p;
for (int j = p; j <r-1; ++j) {
if (vec[j] <= vec[r-1]) {
swap(vec[i], vec[j]);
i++;
}
}
swap(vec[i], vec[r-1]);
return i;
}
void sortVector(vector<int> &vec, int p, int r) {
if (r == -2) {
r = vec.size();
}
if (r>p) {
int q = partition(vec, p, r);
sortVector(vec, p, q);
sortVector(vec, q+1, r);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.