Edexcel International Advanced Level Computer Science, point 21.1.2
The idea of quick sort is in 15.2.2. In Unit 4 you must implement and use a recursive quick sort, and amend it. It picks a pivot, partitions the rest into smaller and larger, and sorts each part recursively.
The structure
quick_sort(list)
base case: fewer than 2 items -> return the list
choose a pivot
partition: smaller = items <= pivot larger = items > pivot
return quick_sort(smaller) + [pivot] + quick_sort(larger)
Version 1: using new lists (clear and short)
def quick_sort(items):
if len(items) <= 1: # base case
return items
pivot = items[len(items) // 2] # the middle item
smaller = [x for x in items if x < pivot]
equal = [x for x in items if x == pivot]
larger = [x for x in items if x > pivot]
return quick_sort(smaller) + equal + quick_sort(larger)
print(quick_sort([7, 2, 9, 4, 1, 8, 4])) # [1, 2, 4, 4, 7, 8, 9]
- The three-way split (
smaller,equal,larger) handles duplicates cleanly and guarantees progress: both sides are strictly smaller than the input. - Using the middle item as the pivot avoids the worst case for sorted data.
- The input list is not changed.
Trace for [7, 2, 9, 4, 1, 8] (pivot = middle item, index 3, value 4):
quick_sort([7, 2, 9, 4, 1, 8]) pivot 4
smaller [2, 1] equal [4] larger [7, 9, 8]
quick_sort([2, 1]) pivot 1 (index 1)
smaller [] equal [1] larger [2] -> [1, 2]
quick_sort([7, 9, 8]) pivot 9 (index 1)
smaller [7, 8] equal [9] larger []
quick_sort([7, 8]) pivot 8 -> smaller [7], equal [8] -> [7, 8]
-> [7, 8, 9]
combine: [1, 2] + [4] + [7, 8, 9] = [1, 2, 4, 7, 8, 9]
Version 2: in place (partitioning within the list)
Saves memory by rearranging the original list.
def partition(items, low, high):
# the last item as the pivot
pivot = items[high]
i = low - 1
for j in range(low, high):
if items[j] <= pivot:
i += 1
items[i], items[j] = items[j], items[i]
items[i + 1], items[high] = items[high], items[i + 1]
# the pivot's final index
return i + 1
def quick_sort_inplace(items, low=0, high=None):
if high is None:
high = len(items) - 1
# base case: 0 or 1 items
if low < high:
p = partition(items, low, high)
quick_sort_inplace(items, low, p - 1) # left of the pivot
quick_sort_inplace(items, p + 1, high) # right of the pivot
return items
data = [7, 2, 9, 4, 1, 8]
quick_sort_inplace(data)
print(data) # [1, 2, 4, 7, 8, 9]
Partition of [7, 2, 9, 4, 1, 8] (pivot = 8, the last item): the items move to the left and the pivot is swapped into place, giving [7, 2, 4, 1, 8, 9] with the pivot at index 4 (15.2.2).
Choosing the pivot
| Choice | Effect |
|---|---|
| First item | Simple, but worst case on sorted data () |
| Last item | The same weakness |
| Middle item | Good for sorted and reversed data |
| Random item | Very unlikely to hit the worst case |
| Median of three (first, middle, last) | A good balance |
import random
def quick_sort_random(items):
if len(items) <= 1:
return items
pivot = random.choice(items)
return (quick_sort_random([x for x in items if x < pivot])
+ [x for x in items if x == pivot]
+ quick_sort_random([x for x in items if x > pivot]))
Amending the algorithm
- Descending order: swap
<and>in the list comprehensions. - Sorting records: compare a key:
x[1] < pivot[1]. - Counting comparisons: add a counter in
partition.
Efficiency
| Case | Time | Cause |
|---|---|---|
| Best / average | Pivot splits the list roughly in half | |
| Worst | The pivot is always the smallest or largest item |
- Space: for the recursion (in place), more for version 1 (new lists).
- Deep recursion in the worst case could cause a
RecursionError(Python's limit is about 1000).
Test plan
| Test | Data |
|---|---|
| Empty | [] |
| One item | [1] |
| Sorted | [1, 2, 3, 4] |
| Reversed | [4, 3, 2, 1] |
| All equal | [5, 5, 5] |
| Duplicates | [3, 1, 3, 2, 1] |
| Negatives | [0, -2, 5, -7] |
tests = [[], [1], [1, 2, 3, 4], [4, 3, 2, 1], [5, 5, 5],
[3, 1, 3, 2, 1], [0, -2, 5, -7]]
for t in tests:
assert quick_sort(t) == sorted(t)
assert quick_sort_inplace(t[:]) == sorted(t)
print("All quick sort tests passed")
Worked example
Task: use quick sort to sort [5, 3, 8, 1, 4], showing the partitions with the middle item as the pivot.
- Pivot = 8 (index 2). Smaller:
[5, 3, 1, 4]. Equal:[8]. Larger:[]. - Sort
[5, 3, 1, 4]: the middle index is 2, so the pivot is 1. Smaller:[]. Equal:[1]. Larger:[5, 3, 4]. - Sort
[5, 3, 4]: pivot = 3 (index 1). Smaller:[], equal:[3], larger:[5, 4]. - Sort
[5, 4]: pivot = 4 (index 1). Smaller:[], equal:[4], larger:[5]. Result[4, 5]. - Combine upwards:
[3] + [4, 5]=[3, 4, 5], then[1] + [3, 4, 5]=[1, 3, 4, 5], then[1, 3, 4, 5] + [8]=[1, 3, 4, 5, 8].
Exam tip: have a base case (len <= 1) and make sure both sub-lists are smaller than the input, or the recursion never ends. Handle duplicates (the three-way split or <= and >). Explain how the pivot choice affects speed (the worst case ). Test sorted, reversed and duplicate lists.
Check yourself
What is the base case of quick sort?
A list with zero or one item, which is already sorted.
Why use the middle item as the pivot instead of the first?
The first item gives the worst case on already sorted data; the middle item splits sorted data evenly.
What happens to duplicates of the pivot in the three-way version?
They go into the equal list, which is already in place and isn't sorted again.
What is the advantage of the in-place version?
It rearranges the original list without creating new lists, so it uses much less memory.