Sorting
Identify sorts from their intermediate states, trace heapify and partitioning, and reason about which sort fits which input.
- Lessons
- Basic sorts · Quicksort and selection
This discussion goes with Lessons 54 and 55.
Q1: What would Swift print?
What would Swift print?
var h = [5, 2, 8, 1, 9, 3]
func sink(_ i: Int, _ n: Int) {
var i = i
while true {
let (l, r) = (2 * i + 1, 2 * i + 2)
var m = i
if l < n && h[l] > h[m] { m = l }
if r < n && h[r] > h[m] { m = r }
if m == i { return }
h.swapAt(i, m)
i = m
}
}
for i in stride(from: h.count / 2 - 1, through: 0, by: -1) {
sink(i, h.count)
}
print(h)Show answer and explanation
Answer[9, 5, 8, 1, 2, 3]
Heapify sinks positions 2, 1, then 0. Position 2 (8) is already larger than its child, 3. Position 1 (2) swaps with its larger child, 9. Then the root, 5, swaps with 9; at position 1 its new children are 1 and 2, both smaller, so it stops. The result is a max-heap with 9 on top, the first step of heapsort.
What would Swift print?
var q = [5, 2, 8, 1, 9, 3]
let pivot = q.last!
var store = 0
for i in 0..<(q.count - 1) where q[i] < pivot {
q.swapAt(i, store)
store += 1
}
q.swapAt(store, q.count - 1)
print(q, store)Show answer and explanation
Answer[2, 1, 3, 5, 9, 8] 2
Lomuto’s partition around 3 moves the two smaller items, 2 and 1, to the front, then puts 3 at position 2, its final place. The items after it are larger, in no particular order.
Q2: Which sort is it?
Each row shows an array after a few steps of some sort, starting from
[5, 2, 8, 1, 9, 3]. Identify the sort: selection, insertion, merge sort (top down),
heapsort, or quicksort with the last item as pivot.
[1, 2, 8, 5, 9, 3], then[1, 2, 8, 5, 9, 3], then[1, 2, 3, 5, 9, 8][2, 5, 8, 1, 9, 3], then[2, 5, 8, 1, 9, 3], then[1, 2, 5, 8, 9, 3][2, 1, 3, 5, 9, 8]- halves
[2, 5, 8]and[1, 3, 9], about to be combined [9, 5, 8, 1, 2, 3]
Show solution
- Selection sort. After step k, the first k items are the k smallest, in order, and each step swapped one item into place.
- Insertion sort. After step k, the first k + 1 items are sorted among themselves, but not necessarily the smallest: 1 is still waiting to be inserted.
- Quicksort, after one partition around 3: smaller items to its left, larger to its right.
- Merge sort: the two sorted halves just before the final merge.
- Heapsort, after heapify: a max-heap, before any item is moved to the end.
Q3: Matching sorts to inputs
Which sort would you choose, and why?
- A list of 1,000,000 timestamps that arrive almost in order.
- Sorting 20 items, millions of times per second.
- Records that must stay in their original order among equal keys, with no extra memory limit.
- A huge array on a device with almost no spare memory, with a guaranteed worst case.
Show solution
- Insertion sort (or Swift’s
sort, which detects runs): Θ(N + inversions), nearly linear here. - Insertion sort: for tiny arrays its tight loop beats every N log N algorithm, which is why hybrids use it for small pieces.
- Merge sort, or Swift’s
sort: stable and Θ(N log N). - Heapsort: Θ(N log N) in the worst case with Θ(1) extra memory. Quicksort also uses little memory, but its worst case is quadratic.
Q4: Exam-level: quicksort’s worst case
- With the first item as pivot, which inputs make quicksort quadratic?
- With the median of the first, middle, and last items as pivot, construct an input of 7 items for which the first partition is as unbalanced as possible.
- Why does choosing the pivot at random make every input fast on average?
Show solution
- Sorted and reverse-sorted arrays, and any array where the first item is repeatedly the smallest or largest of what remains.
- Make the three sampled items the three smallest, with the median of them second
smallest overall:
[2, 5, 6, 1, 7, 4, 3]samples 2, 1, and 3, whose median is 2, and only 1 is smaller than 2. (Adversaries can defeat any fixed rule this way.) - The expected cost depends on the random choices, not on the input: for every input, each pivot lands in the middle half with probability 1/2, so the expected depth is O(log N) and the expected work O(N log N).