I have implemented the classic Hoare's partitioning algorithm for Quicksort. It works with any list of unique numbers [3, 5, 231, 43]. The only problem is when I have a list with duplicates [1, 57, 1, 34]. If I get duplicate values I enter an infinite loop.
private void quicksort(int[]a, int lo, int hi) {
if (lo < hi) {
int q = hoare_partition(a, lo, hi);
quicksort(a, lo, q - 1);
quicksort(a, q + 1, hi);
}
}
private int hoare_partition(int[] a, int lo, int hi) {
int pivot = a[hi];
int i = lo;
int j = hi;
while (true) {
while (a[i] < pivot) i++;
while (a[j] > pivot) j--;
if (i < j) swap(a, i, j);
else return j;
}
}
Is it possible that Hoare's implementation is incorrect and is unable to cope with duplicates?
I know this has been asked many times (and I tried them all) but I am having difficulties figuring the solution for this implementation.
while (a[j] >= pivot)
shall help. – Penneywhile (a[j] >= pivot)
. – Friedmangetting [StackOverflowError]
(remember where you're discussing this?) Recurse into the non-biggest partition, iterate for the other/non-smaller ones. – Taffeta