Edexcel International Advanced Level Computer Science, point 15.2.2
Definition
Quick sort is a divide-and-conquer sorting algorithm (15.1.1). It chooses an item called the pivot, partitions the other items into those smaller than (or equal to) the pivot and those larger, and then sorts each part recursively. The pivot ends up in its final position after each partition.
Function
It sorts a list in time on average, and is often the fastest general-purpose sort in practice.
Characteristics
- Divide and conquer, recursive (Unit 4: 21.1.2).
- Does most of its work while dividing (the partition), and nothing when combining, unlike merge sort (15.2.1).
- Can sort in place (little extra memory).
- Not stable in its usual in-place form.
- Speed depends on the choice of pivot.
Operation
- If the list has 0 or 1 items, it is sorted: stop (the base case).
- Choose a pivot (for example the first item, the last, the middle, or a random one).
- Partition: put the items smaller than or equal to the pivot on its left, and larger items on its right. The pivot is now in its final place.
- Recursively quick sort the left part and the right part.
[7, 2, 9, 4, 1, 8] pivot = 7
smaller or equal: [2, 4, 1] larger: [9, 8]
result so far: [2, 4, 1] 7 [9, 8] (7 is in its final place)
Hand trace: sort [7, 2, 9, 4, 1, 8] (pivot = first item)
Code
A clear version (creates new lists)
def quick_sort(items):
if len(items) <= 1: # base case
return items
pivot = items[0]
smaller = [x for x in items[1:] if x <= pivot]
larger = [x for x in items[1:] if x > pivot]
return quick_sort(smaller) + [pivot] + quick_sort(larger)
print(quick_sort([7, 2, 9, 4, 1, 8])) # [1, 2, 4, 7, 8, 9]
An in-place version (partitioning within the list)
def quick_sort_inplace(items, low=0, high=None):
if high is None:
high = len(items) - 1
if low < high:
p = partition(items, low, high)
quick_sort_inplace(items, low, p - 1)
quick_sort_inplace(items, p + 1, high)
return items
def partition(items, low, high):
pivot = items[high] # pivot = the last item
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]
return i + 1 # the pivot's final index
Partition trace of [7, 2, 9, 4, 1, 8] with the last item (8) as pivot:
j |
items[j] |
<= 8? |
Action | List |
|---|---|---|---|---|
| 0 | 7 | Yes | i = 0, swap with itself |
[7, 2, 9, 4, 1, 8] |
| 1 | 2 | Yes | i = 1 |
[7, 2, 9, 4, 1, 8] |
| 2 | 9 | No | [7, 2, 9, 4, 1, 8] |
|
| 3 | 4 | Yes | i = 2, swap with index 2 |
[7, 2, 4, 9, 1, 8] |
| 4 | 1 | Yes | i = 3, swap with index 3 |
[7, 2, 4, 1, 9, 8] |
| end | swap pivot into i + 1 = 4 |
[7, 2, 4, 1, 8, 9] |
8 is now in its final place (index 4): everything to the left is and everything to the right is larger.
Efficiency and the choice of pivot
| Case | When | Time |
|---|---|---|
| Best | The pivot splits the list into two roughly equal halves each time | |
| Average | Random order | |
| Worst | The pivot is always the smallest or largest item (for example the first item of an already sorted list): one part is empty and the other has |
- Space: for the recursion (in place), or more for the list-building version.
- Choosing the pivot well avoids the worst case:
- Median of three (first, middle and last: take the median).
- A random item.
- The middle item (good for sorted data).
Benefits
- Very fast in practice, average with small constant factors.
- Sorts in place (little extra memory).
- Good cache behaviour.
- No combine step.
Drawbacks
- Worst case with poor pivots.
- Not stable.
- Recursion (stack use; deep recursion for bad pivots).
- More complex than simple sorts, and performance varies with the input.
Quick sort and merge sort compared
| Quick sort | Merge sort | |
|---|---|---|
| Average time | ||
| Worst time | ||
| Extra memory | Little (in place) | |
| Stable? | No | Yes |
| Main work | In the partition (divide) | In the merge (combine) |
| Typical speed | Usually faster | Slightly slower, but predictable |
Worked example
Task: trace the quick sort (first item as pivot) on [5, 3, 8, 1], and say how many recursive levels are needed.
- Pivot 5. Smaller or equal:
[3, 1]. Larger:[8]. - Sort
[3, 1]: pivot 3, smaller[1], larger[], giving[1, 3]. - Sort
[8]: already sorted. - Combine:
[1, 3] + [5] + [8] = [1, 3, 5, 8].
Recursive levels: 3 (the whole list, then [3, 1], then [1]).
What if the list were [1, 3, 5, 8] (already sorted)? With the first item as pivot, each step puts nothing on the left: pivot 1, then 3, then 5: 4 levels and work. Choosing the middle item would avoid that.
Exam tip: explain the partition clearly (smaller to the left, larger to the right, the pivot in its final place) and show the recursion on both parts. State the average () and worst () cases, and what causes the worst case (bad pivot, such as the first item of sorted data). In Unit 4, write the recursive version.
Check yourself
What is a pivot?
The item chosen to divide the list: smaller items go to its left, larger to its right, and it ends up in its final position.
What is the worst-case time of quick sort, and what causes it?
O(n²), when the pivot is always the smallest or largest item, such as the first item of an already sorted list.
Sort [4, 1, 3] with quick sort using the first item as pivot
Pivot 4: smaller [1, 3], larger []. Sort [1, 3]: pivot 1, larger [3] giving [1, 3]. Result [1, 3, 4].
Give one advantage of quick sort over merge sort
It sorts in place with little extra memory, and is usually faster in practice.
How can the worst case be avoided?
Choose the pivot better, such as a random item, the middle item or the median of three.