我有一个运行良好的快速程序,直到我尝试对具有重复数字的数组进行排序。该程序陷入无限循环。我相信这发生在While(lower < upper)
代码块中。
void quickSort(int array[], int size){
if(size < 2) return;
int pivot, lower, upper, temp;
//Set the indeces for the first and last elements
lower = 0;
upper = size - 1;
//Select pivot element randomly
pivot = array[rand() % (size)];
while(lower < upper){
//Lower must be a number < than pivot and upper a number >= pivot
while(array[lower] < pivot){
lower++;
}
while(array[upper] > pivot){
upper--;
}
//Swap upper and lower
temp = array[lower];
array[lower] = array[upper];
array[upper] = temp;
}
//Repeat the past actions on the two partitions of the array recursively
quickSort(array, lower);
quickSort(&array[lower+1], size-lower-1);
}
答案 0 :(得分:6)
编辑:代码已添加。
从Wikipedia开始,就地快速排序的伪代码如下:
(并不是说他们应该盲目信任)
function quicksort(array)
if length(array) > 1
pivot := select any element of array
left := first index of array
right := last index of array
while left ≤ right
while array[left] < pivot
left := left + 1
while array[right] > pivot
right := right - 1
if left ≤ right
swap array[left] with array[right]
left := left + 1
right := right - 1
quicksort(array from first index to right)
quicksort(array from left to last index)
所以你看到它与你的算法非常相似,只需稍作修改。
while(lower <= upper){
此外,您只需要在lower <= upper
时进行交换,然后更新索引。
您的代码在递归调用中有所不同:
quicksort(array from first index to right) {array[0] to array[upper]}
quicksort(array from left to last index) {array[lower] to array[size-1]}
这是因为现在它已经退出了while循环,upper低于低。
完整的工作代码:
#include <iostream>
#include <cstdlib>
using namespace std;
void quickSort(int array[], int size){
if(size < 2) return;
int pivot, lower, upper, temp;
//Set the indeces for the first and last elements
lower = 0;
upper = size - 1;
//Select pivot element randomly
pivot = array[rand() % (size)];
while(lower <= upper){
//Lower must be a number < than pivot and upper a number >= pivot
while(array[lower] < pivot){
lower++;
}
while(array[upper] > pivot){
upper--;
}
//Swap upper and lower
if ( lower <= upper ) {
temp = array[lower];
array[lower] = array[upper];
array[upper] = temp;
lower++;
upper--;
}
}
//Repeat the past actions on the two partitions of the array recursively
quickSort(array, upper+1);
quickSort(&array[lower], size-lower);
}
int main() {
// your code goes here
int myArray[] = { 10, 9, 8, 7, 7, 7, 7, 3, 2, 1};
quickSort( myArray, 10 );
for ( int i = 0; i < 10; i++ )
cout << myArray[i] << " ";
return 0;
}
输出:
1 2 3 7 7 7 7 8 9 10