Sub topic 1
Divide and Conquer: The Idea Behind Quicksort
Prerequisites
This chapter assumes you can write basic Python and use index-based array access. You should also understand recursion and the call stack, read Big-O notation, and know one simple sort, such as insertion sort.
The Divide-and-Conquer Idea
Divide and conquer solves a problem in three steps. You split it into smaller subproblems, solve each one recursively, and combine the results. Quicksort does almost all of its work in the split step. It picks a pivot, which is one element of the array. It then moves smaller elements to the pivot's left and larger ones to its right. Every element ends up on the correct side of the pivot, so sorting each side finishes the job and there is nothing to combine.
The version below is not in place, because it builds new lists. It shows the shape of the algorithm without the details of partitioning.
def quicksort_simple(xs):
if len(xs) <= 1:
return xs
pivot = xs[len(xs) // 2]
less = [x for x in xs if x < pivot]
equal = [x for x in xs if x == pivot]
greater = [x for x in xs if x > pivot]
return quicksort_simple(less) + equal + quicksort_simple(greater)
print(quicksort_simple([5, 3, 8, 1, 9, 2, 5])) # [1, 2, 3, 5, 5, 8, 9]Partitioning Around a Pivot
Partitioning rearranges a range a[lo..hi] so that the pivot sits at some index p. Everything before p is smaller than the pivot, and everything after p is not smaller. The pivot is now at its final sorted position. Real implementations do this in place, using only swaps.
The Lomuto Partition Scheme
Lomuto's scheme uses the last element as the pivot. Index i marks the boundary of the "less than pivot" region. Index j scans the rest of the range. When a[j] is smaller than the pivot, the loop swaps it into the region and moves the boundary forward. At the end, one final swap puts the pivot at index i.
Recursive Quicksort
def lomuto_partition(a, lo, hi):
pivot = a[hi]
i = lo
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]
return i
def quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
p = lomuto_partition(a, lo, hi)
quicksort(a, lo, p - 1)
quicksort(a, p + 1, hi)
data = [5, 3, 8, 1, 9, 2]
quicksort(data)
print(data) # [1, 2, 3, 5, 8, 9]Exercise
Trace the first call to lomuto_partition on [5, 3, 8, 1, 9, 2] with lo=0 and hi=5. What does the array look like afterward, and what index is returned?
Show answer
The pivot is 2. Only the 1 at index 3 is smaller than 2, so it is swapped with a[0], which gives [1, 3, 8, 5, 9, 2] with i=1. The final swap of a[1] and a[5] gives [1, 2, 8, 5, 9, 3], and the function returns 1.