Python 3D Academyবাংলা

Quick sort: partitioning around a pivot

🌍 In real life. A teacher has a messy pile of exam papers to put in order of marks, and no table space for extra piles. She picks one paper, say the one with 58 marks, and calls it the pivot. Then she goes through the rest once: papers below 58 go to the left part, the others stay on the right. She puts the 58 paper between the two parts. Now that paper is exactly where it belongs, and nothing ever needs to cross it again. She does the same to the left part and to the right part, and to their parts, until every part has one paper or none.

This is quick sort. Like merge sort it splits the work in two, but it does the hard work before splitting (the partition), so there is nothing to merge afterwards, and it needs no second list.

The idea in one sentence: quick sort partitions the list around a pivot, so the pivot lands in its final place with smaller values on its left and the rest on its right, then quick sorts each side.

Its words:

  • pivot: the value the list is split around; here the last value of the part
  • partition: rearranging a part so the values smaller than the pivot come first, then the pivot, then the rest
  • Lomuto partition: the way used here: i marks the end of the smaller part, and j walks the part once
  • in place: values are swapped within the list; no second list is made

Partition, step by step:

  1. pivot = a[hi], and i = lo: the smaller part is empty so far
  2. for each j from lo to hi - 1: if a[j] < pivot, swap a[j] to position i, and move i on
  3. at the end, swap the pivot into position i: smaller values on its left, the rest on its right

The pale blue part is smaller than the pivot (orange); pointer i marks where that part ends:

Quick sort, step by step: partition the part lo..hi; the pivot is now at p, in its final place. Quick sort lo..p - 1 and p + 1..hi. A part with one value or none is already sorted. The purple bar shows the part being partitioned:

Why it is correct. During the partition two facts stay true: everything in a[lo:i] is smaller than the pivot, and everything in a[i:j] is not. Each new a[j] either joins the smaller part (swapped to i, and i grows) or simply stays, so both facts still hold. When j reaches the pivot, swapping the pivot to i puts every smaller value on its left and every other value on its right: wherever those values end up, the pivot's place is final. Sorting each side then sorts the whole.

What it costs, by counting. One partition of a part of size m makes m − 1 comparisons. If the pivots split near the middle, the parts halve at each level, so there are about log₂ n levels of about n comparisons each: O(n log n), the average case for a muddled list. But if the pivot is always the biggest or smallest value, each partition peels off just one value: n levels, n(n − 1)/2 comparisons, O(n²). With the last value as the pivot, an already sorted list is exactly this worst case. The fix is to pick a random pivot (swap a random value to hi first): then no particular input is bad, and the expected cost is O(n log n). Quick sort needs no second list, only the call stack (about log₂ n deep on average), and in practice its simple inner loop makes it one of the fastest sorts. It is not stable: the long swaps can carry a value past an equal one.

def partition(a, lo, hi):
    pivot = a[hi]                      # the last value is the pivot
    i = lo                             # a[lo:i] is smaller than the pivot
    for j in range(lo, hi):
        if a[j] < pivot:
            a[i], a[j] = a[j], a[i]
            i += 1
    a[i], a[hi] = a[hi], a[i]          # the pivot goes between the parts
    return i

def quick_sort(a, lo=0, hi=None):
    if hi is None:
        hi = len(a) - 1
    if lo < hi:
        p = partition(a, lo, hi)       # a[p] is now in its final place
        quick_sort(a, lo, p - 1)
        quick_sort(a, p + 1, hi)
    return a

print(quick_sort([5, 2, 8, 1, 9, 3, 7, 4]))

a = [5, 2, 8, 1, 9, 3, 7, 4]
p = partition(a, 0, len(a) - 1)
print(p, a)                            # the pivot 4 is at its final place

import random

def quick_sort_random(a, lo=0, hi=None):
    if hi is None:
        hi = len(a) - 1
    if lo < hi:
        r = random.randint(lo, hi)     # a random pivot: no input is always bad
        a[r], a[hi] = a[hi], a[r]
        p = partition(a, lo, hi)
        quick_sort_random(a, lo, p - 1)
        quick_sort_random(a, p + 1, hi)
    return a

print(quick_sort_random(list(range(20, 0, -1))))

Mistakes and edge cases.

  • recursing on lo..p instead of lo..p - 1: the pivot is included again, and a part can stay the same size forever: RecursionError
  • forgetting the last swap: the pivot never moves into its place, and the parts are wrong
  • a[j] <= pivot: also correct; but with < or <=, a list of many equal values splits badly every time, which is why libraries split into three parts: smaller, equal, bigger
  • a sorted list with the last value as pivot: n levels deep; in Python a long sorted list can even hit the recursion limit; use a random pivot
  • expecting a new list: this quick sort changes the list in place

Quiz

  1. What does this print?

    def partition(a, lo, hi):
        pivot = a[hi]                      # the last value is the pivot
        i = lo                             # a[lo:i] is smaller than the pivot
        for j in range(lo, hi):
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi] = a[hi], a[i]          # the pivot goes between the parts
        return i
    
    a = [7, 2, 9, 4, 5]
    p = partition(a, 0, len(a) - 1)
    print(p, a)
  2. After one partition, what is certain?

    • The pivot is in its final place
    • The left part is sorted
    • The list is half sorted
  3. Quick sort with the last value as the pivot gets a list that is already sorted. What happens?

    • Its worst case: each pivot is the biggest, n levels and about n²/2 comparisons
    • Its best case: n comparisons
    • The same as any other list
  4. This quick sort never finishes on [2, 1, 3]. Which line is wrong?

    def quick_sort(a, lo, hi):
        if lo < hi:
            p = partition(a, lo, hi)
            quick_sort(a, lo, p)
            quick_sort(a, p + 1, hi)
  5. Why might you choose merge sort over quick sort?

    • It is O(n log n) on every input and it is stable
    • It uses less memory
    • It does all its work before splitting

Coding tasks

  1. Write partition(a, lo, hi): use a[hi] as the pivot; move the values of a[lo..hi] smaller than it to the front of that part, put the pivot right after them, and return the pivot's new position. Values outside lo..hi must not move. Within each side, any order is fine.

  2. Write quick_sort(a, lo=0, hi=None): sort a in place with quick sort and return it. partition is given. With hi=None, sort the whole list.

  3. The exam office wants the k-th lowest mark (k = 1 is the lowest) without sorting everything. Write kth_smallest(marks, k): partition, and keep only the side the k-th value must be on, until the pivot lands exactly at position k − 1. partition is given. Work on a copy, so marks is unchanged.