1def partition(a, lo, hi):2 pivot = a[hi]3 i = lo - 14 for j in range(lo, hi):5 if a[j] <= pivot:6 i += 17 a[i], a[j] = a[j], a[i]8 a[i+1], a[hi] = a[hi], a[i+1]9 return i + 1a[0]a[1]a[2]a[3]a[4]a[5]a[6]k = 3pivotcompares01def quicksort(a, lo, hi):2 if lo < hi:3 p = partition(a, lo, hi)4 quicksort(a, lo, p - 1)5 quicksort(a, p + 1, hi)6281594ij
Bars: the list a, one per slot, height = value; a rose bar is a pivot in its final placeTiles: mint = at most the pivot, plum = bigger; i and j are the two indicesA raised bar: the pivot of the partition running nowpartition() on the card splits a[lo..hi] around the pivot a[hi]: j scans, items at most the pivot swap left past the boundary i, and the pivot drops into its final place. quicksort() repeats it on both sides (11 compares here, 21 on sorted input); quickselect keeps only the side that holds index k.

Partition

  1. Quicksort sorts a list by splitting it. Pick one item, the pivot. Move every item that is not bigger to its left and every bigger one to its right. Now the pivot sits in its final place. Then sort each side the same way.

Quicksort

Quickselect

What happens

;; step 1/9 · idea
a = [6, 2, 8, 1, 5, 9, 4]   (n = 7)

def partition(a, lo, hi):
    pivot = a[hi]
    i = lo - 1
    for j in range(lo, hi):
        if a[j] <= pivot:
            i += 1
            a[i], a[j] = a[j], a[i]
    a[i+1], a[hi] = a[hi], a[i+1]
    return i + 1

def quicksort(a, lo, hi):
    if lo < hi:
        p = partition(a, lo, hi)
        quicksort(a, lo, p - 1)
        quicksort(a, p + 1, hi)

quicksort(a, 0, len(a) - 1)
a  ->  [1, 2, 4, 5, 6, 8, 9]

The figure uses Lomuto's partition, the version in CLRS chapter 7: the last item is the pivot and items equal to it go left. Hoare's original scheme scans from both ends and does fewer swaps; Sedgewick and Wayne use a variant of it. A compare is one run of the test a[j] <= pivot. A partition of m items makes m − 1 compares. The 11, 21 and 10 in the figure are real counts from running the Python code.