« Back to all algorithms and all initial conditions

Quick Sort (3 Way Partition)

Problem Size:  20 · 30 · 40 · 50     Magnification:  1x · 2x · 3x
Algorithm:  Insertion · Selection · Bubble · Shell · Merge · Heap · Quick · Quick3

Algorithm

# choose pivot
swap a[n,rand(1,n)]

# 3-way partition
i = 1, 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
→ invariant: a[p..n] all equal
→ invariant: a[1..k-1] < a[p..n] < a[k..p-1]

# move pivots to center
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

  • Not stable
  • O(lg(n)) extra space
  • O(n2) time, but typically O(n·lg(n)) time
  • Adaptive: O(n) time when O(1) unique keys

Discussion

The 3-way partition variation of quick sort has slightly higher overhead compared to the standard 2-way partition version. Both have the same best, typical, and worst case time bounds, but this version is highly adaptive in the very common case of sorting with few unique keys.

When stability is not required, 3-way partition quick sort is the general purpose sorting algorithm of choice.

The 3-way partitioning code shown above is written for clarity rather than optimal performance; it exhibits poor locality, and performs more swaps than necessary. A more efficient but more elaborate 3-way partitioning method is given in Quicksort is Optimal by Robert Sedgewick and Jon Bentley.

Directions

  • Click on above to restart the animations in a row, a column, or the entire table.
  • Click directly on an animation image to start or restart it.
  • Click on a problem size number to reset all animations.

Key

  • Black values are sorted.
  • Gray values are unsorted.
  • Dark gray values denote the current interval.
  • A pair of red triangles mark k and p (see the code).

References

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

Programming Pearls by Jon Bentley. Addison Wesley, 1986.

Quicksort is Optimal by Robert Sedgewick and Jon Bentley, Knuthfest, Stanford University, January, 2002.

Comments

To post a comment, you must log in.
Nice wensite
— posted by someone on 27-Jan-2010
Hi I've finished the dev off a new sorting algorithme witch I called "A.L.E.X." sins few days , and i wona know how to do to register/protect it under a copyright licence. samir L. 2010
— posted by someone on 13-Jan-2010
Two-way bubble sort (shaker sort) is a variation on bubble sort, and isn't different enough (or useful enough) to merit being included here in my opinion. Shaker sort has all the same analytical properties of bubble sort, and is slightly faster in some instances, but shaker sort does not get used in practice as far as I know.
— posted by someone on 20-Dec-2009
hey, may you add the two-way bubblesorting to the comparsion chart?
— posted by someone on 8-Dec-2009