I have been searching for this in many questions related to 3 way quicksort but could not find an answer/explanation (like this and similar - Quicksort with 3-way partition).
Below is the 3-ways quick sort code from Robert Sedgewick and Kevin Wayne book "Algorithms".
private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo) return;
int lt = lo, gt = hi;
Comparable v = a[lo];
int i = lo;
while (i <= gt) {
int cmp = a[i].compareTo(v);
if (cmp < 0) exch(a, lt++, i++);
else if (cmp > 0) exch(a, i, gt--);
else i++;
}
sort(a, lo, lt-1);
sort(a, gt+1, hi);
}
After partitioning, elements left to the pivot should be lesser than the pivot and those on right greater than the pivot. Elements equal to pivot should be together in the middle. I have tried writing the above code each step-wise in detail but am unable to understand why i is not incremented when the element is greater than the pivot. It is incremented when the element is less than the pivot:
else if (cmp > 0) exch(a, **i, gt--**);
It would be great if someone could explain this partitioning scheme.