I have a quicksort program that works great until I try to sort an array that has a repeating number. The program gets stuck in an infinite loop. I believe this is happening in the While(lower < upper)
block of code.
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);
}
See Question&Answers more detail:os