【发布时间】:2015-11-15 01:35:09
【问题描述】:
我在我的代码中找不到问题。它运行,但无法正确排序数组。我认为最让我困惑的部分是如何在递归过程中传递未排序的子数组。
#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;
}
输出是这样的:
37 2 6 4 89 8 10 12 68 45
4 6 8 10 12 37 68 89 2 45
【问题讨论】:
-
您可以在本主题查看解决方案:stackoverflow.com/questions/22504837/…
-
我不太确定这是否有助于 OP 的 his 解决方案。我错过了什么吗?
标签: c++ pointers pivot quicksort partition