Dutch National Flag visualization

Three-way partition around a pivot (< pivot | = pivot | > pivot) in one pass.

Three pointers: everything before lo is < pivot, lo..mid−1 equals the pivot, after hi is > pivot, and mid..hi is unknown. Each step classifies A[mid].

This is the trick behind 3-way quicksort, which stays fast on arrays with many duplicates. Edge cases: pivot absent, all equal, all smaller.

Complexity

Time: best O(n), average O(n), worst O(n). Space: O(1). Difficulty: Intermediate.

Pseudocode

procedure partition3(A, pivot):
  lo ← 0; mid ← 0; hi ← n − 1
  while mid ≤ hi:
    if A[mid] < pivot: swap(A[lo], A[mid]); lo++; mid++
    else if A[mid] = pivot: mid++
    else: swap(A[mid], A[hi]); hi−−     // do not advance mid

More techniques algorithms