Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

Quicksort and selection

Sorting by partitioning: quicksort, its best, worst, and average cases, why random pivots make the worst case vanishingly rare, in-place partitioning with Hoare’s scheme, three-way partitioning for duplicates, and quickselect for medians.

CS61B
Quicksort · Textbook Ch. 30, Ch. 31
Swift book
Closures

Tony Hoare invented quicksort in 1959, while trying to sort words for a machine translation program. Its worst case is quadratic, like selection sort. Yet for decades it was the fastest general-purpose sort in practice, and its partitioning idea solves other problems too. CS61B spends two lectures on it, and this lesson covers both.

Partitioning

To partition an array around a pivot item is to rearrange it so that everything smaller than the pivot comes first, then the pivot, then everything larger. The pivot is then in its final sorted position, and neither side needs anything from the other.

Quicksort partitions around a pivot, then quicksorts each side:

var comparisons = 0

func quicksort(_ items: [Int]) -> [Int] {
    guard let pivot = items.first else { return [] }
    var smaller: [Int] = [], equal: [Int] = [], larger: [Int] = []
    for item in items {
        comparisons += 1
        if item < pivot { smaller.append(item) }
        else if item > pivot { larger.append(item) }
        else { equal.append(item) }
    }
    return quicksort(smaller) + equal + quicksort(larger)
}

print(quicksort([5, 3, 8, 1, 9, 2, 7]), comparisons)   // [1, 2, 3, 5, 7, 8, 9] 18

This version is easy to read and uses extra arrays; the in-place version below is what real implementations do. Either way, the work is in the partitioning, and the question is how evenly each pivot splits the array.

Best, worst, and average

  • Best case: every pivot is the median, so each partition splits the array in half. That is merge sort’s recurrence, T(N) = 2T(N/2) + N: Θ(N log N).
  • Worst case: every pivot is the smallest or largest item, so one side is empty. The recurrence becomes T(N) = T(N − 1) + N: Θ(N²). Choosing the first item as the pivot hits this on a sorted array, which is common.
  • Average case: with pivots that are random relative to the data, a pivot is usually somewhere in the middle half, and even an unbalanced split like 1:9 gives depth O(log N). The expected number of comparisons is about 2N ln N ≈ 1.39 N log₂ N.
var comparisons = 0

func quicksort(_ items: [Int], randomPivot: Bool) -> [Int] {
    guard items.count > 1 else { return items }
    let pivot = randomPivot ? items.randomElement()! : items[0]
    var smaller: [Int] = [], equal: [Int] = [], larger: [Int] = []
    for item in items {
        comparisons += 1
        if item < pivot { smaller.append(item) } else if item > pivot { larger.append(item) } else { equal.append(item) }
    }
    return quicksort(smaller, randomPivot: randomPivot) + equal + quicksort(larger, randomPivot: randomPivot)
}

let sorted = Array(0..<2_000)
comparisons = 0
_ = quicksort(sorted, randomPivot: false)
let firstPivot = comparisons
comparisons = 0
_ = quicksort(sorted, randomPivot: true)
let random = comparisons
print(firstPivot == 2_000 * 2_001 / 2 - 1, random < 2_000 * 30)   // true true

On sorted input, the first-item pivot makes 2,000 + 1,999 + … + 2 comparisons, about two million, while random pivots need a few tens of thousands. With random pivots, no input is bad: the worst case can still happen, but only through extraordinarily bad luck, with a probability that shrinks exponentially with N. Randomization turns “bad on some inputs” into “bad on no input, with negligible probability”.

What would Swift print?

var depth = 0
var deepest = 0
func sort(_ items: [Int]) -> [Int] {
    guard let pivot = items.first else { return [] }
    depth += 1
    deepest = max(deepest, depth)
    defer { depth -= 1 }
    return sort(items.filter { $0 < pivot }) + [pivot] + sort(items.filter { $0 > pivot })
}
_ = sort([4, 2, 6, 1, 3, 5, 7])
let balanced = deepest
deepest = 0
_ = sort([1, 2, 3, 4, 5, 6, 7])
print(balanced, deepest)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer3 7

With 4 as the first pivot, then 2 and 6, the recursion is a balanced tree of depth 3. On sorted input, each pivot is the smallest, so the recursion goes seven levels deep, one per item: the call stack itself grows linearly, which for a million items would overflow it.

Partitioning in place

Allocating new arrays costs time and memory. Hoare partitioning rearranges the array itself, with two indices moving toward each other: the left one skips items smaller than the pivot, the right one skips larger items, and when both stop, the two items are swapped:

func partition(_ a: inout [Int], _ low: Int, _ high: Int) -> Int {
    let pivot = a[(low + high) / 2]
    var i = low - 1
    var j = high + 1
    while true {
        repeat { i += 1 } while a[i] < pivot
        repeat { j -= 1 } while a[j] > pivot
        if i >= j { return j }
        a.swapAt(i, j)
    }
}

func quicksort(_ a: inout [Int], _ low: Int, _ high: Int) {
    guard low < high else { return }
    let split = partition(&a, low, high)
    quicksort(&a, low, split)
    quicksort(&a, split + 1, high)
}

var values = [9, 4, 7, 1, 8, 2, 2, 6, 3]
quicksort(&values, 0, values.count - 1)
print(values)   // [1, 2, 2, 3, 4, 6, 7, 8, 9]

After the loop, everything in low...j is at most the pivot and everything in (j + 1)...high at least the pivot, so the two ranges can be sorted separately. Both indices stop at items equal to the pivot and swap them, which sounds wasteful, but keeps splits balanced when there are many duplicates. Choosing the middle item as the pivot handles sorted input well; random choice is safer still.

Quicksort in place uses no extra array, only the recursion’s stack, and its inner loops walk through adjacent memory with simple comparisons. That is why it is fast in practice. It is not stable: swaps move items past equal ones.

Three-way partitioning

When an array has many duplicates, such as sorting people by birth year, splitting into three parts, less than, equal to, and greater than the pivot, puts all the equal items in their final place at once, and the recursion never touches them again. The simple version at the start of this lesson already did this with its equal array; Dijkstra’s “Dutch national flag” algorithm does it in place.

Quickselect

To find the median, or in general the k-th smallest item, there is no need to sort. Partition around a pivot; if the pivot lands at position k, it is the answer, and otherwise the answer is on one side, so recurse on that side only:

func quickselect(_ values: [Int], _ k: Int) -> Int {
    var items = values
    var (low, high) = (0, items.count - 1)
    var random = SystemRandomNumberGenerator()
    while low < high {
        items.swapAt(Int.random(in: low...high, using: &random), high)
        let pivot = items[high]
        var store = low
        for i in low..<high where items[i] < pivot {
            items.swapAt(i, store)
            store += 1
        }
        items.swapAt(store, high)             // the pivot, in its final position
        if store == k { return items[k] }
        if store < k { low = store + 1 } else { high = store - 1 }
    }
    return items[k]
}

let data = [7, 1, 9, 3, 5, 8, 2]
print(quickselect(data, 3), quickselect(data, 0), quickselect(data, 6))   // 5 1 9

Each step discards one side, so with random pivots the expected work is N + N/2 + N/4 + … ≈ 2N: Θ(N) on average, faster than sorting. This partition is Lomuto’s scheme, simpler than Hoare’s: it moves smaller items to the front and places the pivot, taken from the end, right after them.

Put the lines in order

Put the lines in order so the program prints [1, 2] 3 [5, 4].

  1. let items = [3, 5, 1, 4, 2]
  2. print(smaller, pivot, larger)
  3. let (smaller, larger) = (items.filter { $0 < pivot }.sorted(), items.filter { $0 > pivot })
  4. let pivot = items[0]

Show the correct program
let items = [3, 5, 1, 4, 2]
let pivot = items[0]
let (smaller, larger) = (items.filter { $0 < pivot }.sorted(), items.filter { $0 > pivot })
print(smaller, pivot, larger)

Lab 54: Quicksort

Q0: What would Swift print?

What would Swift print?

var a = [3, 8, 2, 5, 1, 4]
let pivot = a[a.count - 1]
var store = 0
for i in 0..<(a.count - 1) where a[i] < pivot {
    a.swapAt(i, store)
    store += 1
}
a.swapAt(store, a.count - 1)
print(a, store)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer[3, 2, 1, 4, 8, 5] 3

Lomuto’s partition moves every item smaller than the pivot, 4, to the front, in the order they are found: 3, 2, 1. The pivot then swaps into position 3, right after them, and the larger items end up after it, in whatever order the swaps left them.

Q1: Sorting in place, tested

Put the lesson’s in-place quicksort (Hoare partitioning, middle pivot) into a function quicksort(_:) that sorts a whole array, and test it against sorted() on random arrays, including ones with many duplicates, and on sorted and reversed arrays.

Show solution
func quicksort(_ a: inout [Int]) {
    func partition(_ low: Int, _ high: Int) -> Int {
        let pivot = a[(low + high) / 2]
        var i = low - 1, j = high + 1
        while true {
            repeat { i += 1 } while a[i] < pivot
            repeat { j -= 1 } while a[j] > pivot
            if i >= j { return j }
            a.swapAt(i, j)
        }
    }
    func sort(_ low: Int, _ high: Int) {
        guard low < high else { return }
        let split = partition(low, high)
        sort(low, split)
        sort(split + 1, high)
    }
    sort(0, a.count - 1)
}

var generator = SystemRandomNumberGenerator()
var cases: [[Int]] = [[], [1], Array(0..<500), Array((0..<500).reversed()), Array(repeating: 7, count: 300)]
for _ in 0..<50 {
    cases.append((0..<Int.random(in: 0...200, using: &generator)).map { _ in Int.random(in: 0..<10, using: &generator) })
}
for values in cases {
    var copy = values
    quicksort(&copy)
    assert(copy == values.sorted())
}

Arrays of equal items are a classic trap: a partition that sends all equal items to one side makes such arrays quadratic. Hoare’s scheme stops at equal items on both sides, so an array of 300 sevens still splits in half.

Q2: The median, fast

Use quickselect to write median(_:) for arrays of odd length, and check it against sorting on random arrays. Count the comparisons for a million items, and compare with the roughly 20 million that sorting would need.

Show solution
var comparisons = 0

func quickselect(_ values: [Int], _ k: Int) -> Int {
    var items = values
    var (low, high) = (0, items.count - 1)
    var random = SystemRandomNumberGenerator()
    while low < high {
        items.swapAt(Int.random(in: low...high, using: &random), high)
        let pivot = items[high]
        var store = low
        for i in low..<high {
            comparisons += 1
            if items[i] < pivot { items.swapAt(i, store); store += 1 }
        }
        items.swapAt(store, high)
        if store == k { return items[k] }
        if store < k { low = store + 1 } else { high = store - 1 }
    }
    return items[k]
}

func median(_ values: [Int]) -> Int {
    precondition(values.count % 2 == 1)
    return quickselect(values, values.count / 2)
}

var generator = SystemRandomNumberGenerator()
for _ in 0..<50 {
    let values = (0..<(2 * Int.random(in: 0...50, using: &generator) + 1)).map { _ in Int.random(in: 0..<100, using: &generator) }
    assert(median(values) == values.sorted()[values.count / 2])
}
comparisons = 0
let big = (0..<1_000_001).map { _ in Int.random(in: 0..<1_000_000, using: &generator) }
_ = median(big)
assert(comparisons < 8_000_000)      // typically around 3 to 4 million

Each round discards the side that cannot contain the k-th item, so the total is a geometric sum, a small multiple of N.

Q3: Three-way partitioning in place

Write Dijkstra’s three-way partition: one pass that rearranges an array into items less than, equal to, and greater than a pivot, with three indices: lt, i, and gt. Use it in a quicksort, and count how many elements the recursion processes on an array of 10,000 items with only 3 distinct values.

Show solution
var processed = 0

func quicksort3(_ a: inout [Int], _ low: Int, _ high: Int) {
    guard low < high else { return }
    processed += high - low + 1
    let pivot = a[low]
    var (lt, i, gt) = (low, low, high)
    // Invariant: a[low..<lt] < pivot, a[lt..<i] == pivot, a[(gt + 1)...high] > pivot.
    while i <= gt {
        if a[i] < pivot { a.swapAt(lt, i); lt += 1; i += 1 }
        else if a[i] > pivot { a.swapAt(i, gt); gt -= 1 }
        else { i += 1 }
    }
    quicksort3(&a, low, lt - 1)
    quicksort3(&a, gt + 1, high)
}

var generator = SystemRandomNumberGenerator()
var values = (0..<10_000).map { _ in Int.random(in: 0..<3, using: &generator) }
let expected = values.sorted()
quicksort3(&values, 0, values.count - 1)
assert(values == expected)
assert(processed < 3 * 10_000)

After the first partition, all items equal to the pivot are done, a third of the array. The two other sides each have one or two distinct values left, so the recursion ends after a few levels: linear work overall, where a two-way quicksort on this input does Θ(N log N) or worse.

Q4 (optional): Making quicksort stable

Quicksort is not stable. Make any sort stable by sorting pairs of (item, original position), comparing positions when items are equal. Check it with Hoare quicksort on records with equal keys.

Show solution
func unstableSort<T>(_ a: inout [T], by less: (T, T) -> Bool) {
    func partition(_ low: Int, _ high: Int) -> Int {
        let pivot = a[(low + high) / 2]
        var i = low - 1, j = high + 1
        while true {
            repeat { i += 1 } while less(a[i], pivot)
            repeat { j -= 1 } while less(pivot, a[j])
            if i >= j { return j }
            a.swapAt(i, j)
        }
    }
    func sort(_ low: Int, _ high: Int) {
        guard low < high else { return }
        let split = partition(low, high)
        sort(low, split)
        sort(split + 1, high)
    }
    sort(0, a.count - 1)
}

func stableSort<T>(_ items: [T], by less: (T, T) -> Bool) -> [T] {
    var tagged = Array(items.enumerated())
    unstableSort(&tagged) { a, b in
        less(a.element, b.element) || (!less(b.element, a.element) && a.offset < b.offset)
    }
    return tagged.map(\.element)
}

let records = (0..<200).map { (key: $0 % 5, id: $0) }
let sorted = stableSort(records) { $0.key < $1.key }
for (a, b) in zip(sorted, sorted.dropFirst()) {
    assert(a.key < b.key || (a.key == b.key && a.id < b.id))
}

The original position breaks every tie, so no two tagged items are equal, and any correct sort must put equal keys in their original order. The cost is an extra integer per item.

What’s next

Merge sort, heapsort, and quicksort all take N log N comparisons. Next lesson asks whether any sort could do better, and proves the answer is no.