« Back to full matrix

Animated Sorting Algorithm Demo: 3-Way Partition Quick Sort

Size:  20 · 30 · 40 · 50 ·
Algorithm:  Insertion · Selection · Bubble · Shell · Merge · Heap · Quick · Quick3

Algorithm

# 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]
        

Properties

Discussion

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.

Directions

Key

References

Algorithms in Java, Parts 1-4, 3rd edition by Robert Sedgewick. Addison Wesley, 2003.

Programming Pearls by Jon Bentley. Addison Wesley, 1986.