C++ 快速排序无法正常工作
我在代码中找不到问题。它运行,但无法正确排序数组。我认为最让我困惑的部分是如何在递归过程中传递未排序的子数组C++ 快速排序无法正常工作,c++,pointers,pivot,quicksort,partition,C++,Pointers,Pivot,Quicksort,Partition,我在代码中找不到问题。它运行,但无法正确排序数组。我认为最让我困惑的部分是如何在递归过程中传递未排序的子数组 #include<iostream> using namespace std; void quickSort(int*, int, int); int partition(int*, int, int); int main(){ int const size = 10; int a[size] = {37, 2, 6, 4, 89, 8, 10, 12,
#include<iostream>
using namespace std;
void quickSort(int*, int, int);
int partition(int*, int, int);
int main(){
int const size = 10;
int a[size] = {37, 2, 6, 4, 89, 8, 10, 12, 68, 45};
for(int i=0; i<size; i++){
cout << a[i] << " ";
}
quickSort(a, 0, size-1);
cout << endl;
for(int i=0; i<size; i++){
cout << a[i] << " ";
}
}
void quickSort(int *array, int start, int end){
if(start<end){
int piv = partition(array, start, end);
quickSort(array, 0, piv-1);
quickSort(array, piv+1, end-1);
}
}
int partition(int *array, int start, int end){
int piv = array[start];
int i = start+1;
int j = end;
while(i<j){
while(array[i]<piv and i<end) i++;
while(array[j]>piv) j--;
if(i<j){
int temp = *(array+i);
*(array+i) = *(array+j);
*(array+j) = temp;
}
}
int temp = *array;
*array = *(array+j);
*(array+j) = temp;
return j;
}
请记住,
end
是包含的,因此您不应该在end-1
上递归,而应该在end
上递归
您的partition()
函数犯了几个错误:
- 在嵌套的while循环中,您应该检查
i我注意到的第一件事是:
应该是:quickSort(array, 0, piv-1); quickSort(array, piv+1, end-1);
quickSort(array, start, piv-1); // start, not 0 quickSort(array, piv+1, end); // end, not end-1
在那之后,我认为在代码的关键位置添加int temp = *(array+start); *(array+start) = *(array+j); *(array+j) = temp;
语句将更容易识别问题的根源。这就是我所尝试的:cout
这让我在void quickSort(int *array, int start, int end){ if(start<end){ cout << "Before sort: "; for(int i=start; i<=end; i++){ cout << array[i] << " "; } cout << std::endl; int piv = partition(array, start, end); std::cout << "Pivot index: " << piv << ", Pivot element: " << array[piv] << std::endl; quickSort(array, start, piv-1); quickSort(array, piv+1, end); } cout << "After sort: "; for(int i=start; i<=end; i++){ cout << array[i] << " "; } cout << std::endl; }
中仔细观察,我注意到您:分区
这就解释了为什么分区数组的下半部分的数字会被拉入分区数组的上半部分。它们应该是:int temp = *array; *array = *(array+j); *(array+j) = temp;
quickSort(array, start, piv-1); // start, not 0 quickSort(array, piv+1, end); // end, not end-1
我更易于阅读:int temp = *(array+start); *(array+start) = *(array+j); *(array+j) = temp;
int temp = array[start]; array[start] = array[j]; array[j] = temp;
通过这些更改,数组得到了排序。您可以在本主题中查看解决方案:但我不确定这是否有助于OP解决方案。我错过什么了吗?