If I were to sort the list of numbers 1,7,5,7,1 using Hoare's algorithm as described at the very beginning of wikipedia item on Hoare partition scheme with 5 being the pivot, and the indexes start at 1 and 1, then what would happen? If they are switched, nothing is really sorted. And the same goes for the two indexes both landing on numbers greater than the pivot, for example, 7 and 7. How would Hoare's algorithm handle such a case?
2 Answers
You've misunderstood the algorithm and it doesn't have the behaviour you suggest.
Let the pivot value be $p$. The algorithm searches from the left for a value $\ell\geq p$ and from the right for a value $r\leq p$. It then only swaps them if they're in the wrong order relative to each other, i.e., if $\ell>r$, so it will never exchange two identical array elements.
In your example, the algorithm would either swap the 1 on the left with the 7 on the right, or the 7 on the left with the 1 on the right, depending on exactly how it is implemented.
- 82,470
- 26
- 145
- 239
Here is the pseudocode at wikipedia on quicksort using the Hoare partition scheme:
algorithm quicksort(A, lo, hi) is
if lo < hi then
p := partition(A, lo, hi)
quicksort(A, lo, p)
quicksort(A, p + 1, hi)
algorithm partition(A, lo, hi) is
pivot := A[lo]
i := lo - 1
j := hi + 1
loop forever
do i := i + 1 while A[i] < pivot
do j := j - 1 while A[j] > pivot
if i >= j then
return j
swap A[i] with A[j]
The indexes never start at the same number in partition:
hi is at least lo+1 (j is at least i+3).
They start indexing "from the ends" to "meet in the middle".
Assuming the list a, g, e, g, a from the question, indexing starting at 1 and pivot "magically" assuming e (the pseudo-code shown would set it to a), i gets initialised to 0 and i to 6 in the first execution of partition.
The 1st "do - while" in the "forever-loop" would set i to 1 unconditionally and to 2 because A[i], which is A[1], (a) is smaller than pivot(e).
The 2nd "do - while" would stop right after setting j to 5:
A[5] already is smaller than pivot.
i is smaller than j: partition isn't done
i and j index a pair of elements in A deserving a swap - guess what?