Partition
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.
partition(a, lo, hi) works on the slice from index lo to hi, here 0 to 6. The last item, 4, is the pivot. A boundary i starts just left of the slice, at −1: no item is known to be small yet.
j walks from lo to hi − 1, comparing each item with the pivot. 6 is bigger: leave it. 2 is not: move i one step right, then swap a[i] and a[j]. Same for 1. After 6 compares, 2 and 1 sit on the left.
The loop ends. a[0..1] holds items at most 4; a[2..5] holds bigger ones. One last swap moves the pivot to index i + 1 = 2. partition returns 2, which is exactly where 4 belongs in the sorted list.
The proof is a loop invariant. Before each pass, a[lo..i] ≤ pivot and a[i+1..j−1] > pivot. It holds at the start, when both zones are empty, and each pass keeps it. At the end j = hi, so every item is on the right side.
Quicksort
quicksort calls itself on the two sides, a[0..1] and a[3..6]. Each call partitions its slice and fixes one more pivot. A slice of 0 or 1 items is already sorted. The whole list is sorted after 11 compares.
Now sort the sorted list. The last item is always the biggest, so each split puts every other item on one side. Compares: 6 + 5 + 4 + 3 + 2 + 1 = 21, which is n(n − 1)/2: Θ(n²).
The fix: pick the pivot at random and swap it to the end first. Here randint picks index 3, the 5: a 3 and 3 split. Random pivots give expected Θ(n log n) compares on every input, 13.5 on average for n = 7.
Quickselect
Quickselect finds the k-th smallest without sorting. Want k = 3. The first pivot lands at 2, so the answer lies to its right: drop the left side. Two more partitions put 5 at index 3. With random pivots, keeping one side costs expected Θ(n).
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.