|
|
|
|
|
# choose pivot
i = rand(1,n)
swap a[i,n]
# 3-way partition
k = 1, p = n
while i < p,
if a[i] < a[n], swap a[i++,k++]
else if a[i] == a[n], swap a[i,--p]
else i++
end
m = min(p-k,n-p+1)
swap a[k..k+m-1,n-m+1..n]
# recursive sorts
sort a[1..k-1]
sort a[n-p+k+1,n]
The 3-way partition variation of quicksort has slightly higher overhead compared to the standard 2-way parition version. Both have the same best, typical, and worst case time bounds, but this version does not exhibit quadratic behavior in the common case of sorting with few unique keys. The benefit of avoiding quadratic time more than offsets the minor increase in overhead.
to restart the animations.
Algorithms in Java, Parts 1-4, 3rd edition by Robert Sedgewick. Addison Wesley, 2003.
Programming Pearls by Jon Bentley. Addison Wesley, 1986.