我使向量类实现了快速排序算法:
class myVector{
//...
private:
T* ptr;//the array
void quick_sort(int low, int high,bool(*compare_func)(const T& left, const T& right)) {
if (low < high) {
int pi = partition(low, high,compare_func);
quick_sort(low, pi - 1,compare_func);
quick_sort(pi + 1, high,compare_func);
}
}
int partition(int low, int high,,bool(*compare_func)(const T& left, const T& right)) {
const T& pivot = ptr[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (compare_func(ptr[j], pivot)) {
i++;
std::swap(ptr[i], ptr[j]);
}
}
std::swap(ptr[i + 1], ptr[high]);
return i + 1;
}
};
比较功能如下:
myVector<float> myArray;
//...
bool compare(const float& left,const float& right) {
return right > left;
}
当向量的大小很小时(例如1000左右),它可以正常工作。但是当向量的大小增加到10000左右时,程序开始以错误代码退出。 我试图更改
for (int j = low; j <= high - 1; j++)
至
for (int j = low; j <= high - 2; j++)
并且程序正常运行,但是当向量的大小达到100000左右时,错误代码再次出现。 有人知道我在哪里做错了吗?谢谢您的帮助。