I tried to implement Quicksort. It works fine except when there is a duplicate key, in which case there is an infinite loop and it never terminates. Can you help me understand what I am doing wrong?
// quick sort
void quickSort(int arr[], const unsigned size)
{
// base case
if (size < 2)
return;
int pivot = arr[size / 2];
unsigned L = 0, U = size - 1;
// partitioning
while (L < U) {
while (arr[L] < pivot)
L++;
while (arr[U] > pivot)
U--;
swap(&arr[L], &arr[U]);
}
quickSort(arr, L); // sort left array
quickSort(&arr[U + 1], size - L - 1); // sort right array
}
You have the less than and greater than conditions. But there is no condition for =
. This is why it will run an infinite loop. Change them to <=
and >=
.