Basic sorts
What sorting means, inversions and stability, and four algorithms with their trade-offs: selection sort, heapsort in place, merge sort, and insertion sort, which is fast on nearly sorted data.
Sorting is the most studied problem in computer science, because so much depends on it: binary search needs sorted data, duplicates become neighbors, and many problems become easy once their input is in order. CS61B devotes five lectures to it. This lesson covers the basic algorithms, each built from an idea earlier lessons already used; the next two cover quicksort and the limits of sorting.
What sorting means
A sort puts items in order by some ordering: < for Comparable values, or a
comparator (Lesson 32). The order must behave: it must be a total order, where any
two items are comparable and the order is transitive, or no algorithm can be correct.
Two ideas measure how far from sorted an array is, and how a sort treats equal items:
- An inversion is a pair of items in the wrong order relative to each other.
[3, 1, 2]has two: (3, 1) and (3, 2). A sorted array has none, and a reversed one has the maximum, N(N − 1)/2. Sorting is removing inversions. - A sort is stable if items that compare equal keep their original relative order. Sorting students by grade with a stable sort keeps each grade’s students in alphabetical order, if they started that way.
func inversions(_ values: [Int]) -> Int {
var count = 0
for i in values.indices {
for j in values.indices where i < j && values[i] > values[j] {
count += 1
}
}
return count
}
print(inversions([3, 1, 2]), inversions([1, 2, 3]), inversions([4, 3, 2, 1])) // 2 0 6
Selection sort
Find the smallest item, swap it to the front, and repeat on the rest: Lesson 27’s test-driven example. It always makes N(N − 1)/2 comparisons, whatever the input: Θ(N²) in every case. It makes few swaps, at most N − 1, but is too slow for large arrays.
Heapsort
Selection sort spends linear time finding each smallest item. A heap finds it in logarithmic time. The naive version inserts everything into a min-heap (Lesson 41) and removes the minimum N times: Θ(N log N), but with a second array for the heap.
In-place heapsort avoids the extra memory. Turn the array itself into a max-heap with Lesson 41’s linear-time heapify, then repeatedly swap the largest item, at the root, with the last item of the heap, shrink the heap by one, and sink the new root. The sorted part grows from the back:
func heapsort(_ items: inout [Int]) {
func sink(_ i: Int, _ size: Int) {
var i = i
while true {
let (l, r) = (2 * i + 1, 2 * i + 2)
var largest = i
if l < size && items[l] > items[largest] { largest = l }
if r < size && items[r] > items[largest] { largest = r }
if largest == i { return }
items.swapAt(i, largest)
i = largest
}
}
for i in stride(from: items.count / 2 - 1, through: 0, by: -1) {
sink(i, items.count) // heapify: a max-heap
}
for end in stride(from: items.count - 1, to: 0, by: -1) {
items.swapAt(0, end) // the largest goes to its final place
sink(0, end)
}
}
var values = [5, 2, 9, 1, 7, 3, 8]
heapsort(&values)
print(values) // [1, 2, 3, 5, 7, 8, 9]
Heapsort is Θ(N log N) in the worst case and uses Θ(1) extra memory. It is not stable, and in practice slower than it sounds, because sinking jumps around the array and defeats the memory caches (Lesson 30).
Merge sort
Lesson 36 built merge sort: split in half, sort each half recursively, and merge. It is Θ(N log N) in every case, and stable, if the merge takes from the left half when two items are equal. Its cost is Θ(N) extra memory for merging. Merge sort is also the natural choice for data too large for memory, or arriving in sorted runs: merging only ever reads each input from front to back.
Insertion sort
Insertion sort builds the sorted result one item at a time, as people sort a hand of cards: take the next item and shift it left past every larger item before it.
var swaps = 0
func insertionSort(_ items: inout [Int]) {
for i in items.indices.dropFirst() {
var j = i
while j > 0 && items[j - 1] > items[j] {
items.swapAt(j - 1, j)
swaps += 1
j -= 1
}
}
}
var shuffled = [5, 2, 9, 1, 7]
insertionSort(&shuffled)
print(shuffled, swaps) // [1, 2, 5, 7, 9] 5
Each swap removes exactly one inversion: it exchanges two neighbors that were in the wrong order, and changes nothing else. So insertion sort makes as many swaps as the array has inversions, and takes Θ(N + K) time for K inversions. On a random array, K is about N²/4, so it is quadratic. But on an almost sorted array, with few inversions, it is nearly linear, faster than any N log N sort.
It is also very fast on small arrays, since its inner loop is tiny and walks through adjacent memory. That is why practical sorts, including Swift’s, switch to insertion sort for short pieces of the array.
What would Swift print?
var items = [1, 2, 3, 5, 4, 6, 7]
var swaps = 0
for i in items.indices.dropFirst() {
var j = i
while j > 0 && items[j - 1] > items[j] {
items.swapAt(j - 1, j)
swaps += 1
j -= 1
}
}
print(swaps)Show answer and explanation
Answer1
The array has one inversion, (5, 4), so insertion sort makes exactly one swap. It still compares each item with its left neighbor once, so its time is Θ(N + K) = Θ(N) here.
The trade-offs
| Sort | Best case | Worst case | Extra memory | Stable |
|---|---|---|---|---|
| Selection | Θ(N²) | Θ(N²) | Θ(1) | no |
| Heapsort | Θ(N log N)* | Θ(N log N) | Θ(1) | no |
| Merge sort | Θ(N log N) | Θ(N log N) | Θ(N) | yes |
| Insertion | Θ(N) | Θ(N²) | Θ(1) | yes |
* Θ(N) if all items are equal.
No single sort wins everywhere, which is why library sorts are hybrids. Swift’s
sort() is a merge sort variant that finds existing runs of sorted data, uses
insertion sort for short runs, and merges: fast on real data, which is often
partly sorted. Its documentation guarantees two things: O(N log N) time, and
stability. So sorting students by grade with sorted(by:) keeps each grade’s
students in their original order. (Lesson 56’s lab shows how to make an unstable sort,
such as quicksort, stable.)
Put the lines in order
Put the lines in order so the program prints [1, 2, 3].
}var j = iprint(items)for i in 1..<items.count {var items = [3, 1, 2]j -= 1items.swapAt(j - 1, j)while j > 0 && items[j - 1] > items[j] {}
Show the correct program
var items = [3, 1, 2]
for i in 1..<items.count {
var j = i
while j > 0 && items[j - 1] > items[j] {
items.swapAt(j - 1, j)
j -= 1
}
}
print(items)Lab 53: Basic sorts
Q0: What would Swift print?
What would Swift print?
struct Student {
let name: String
let grade: Int
}
let students = [Student(name: "Ada", grade: 90), Student(name: "Bo", grade: 85), Student(name: "Cy", grade: 90)]
var sorted = students
for i in sorted.indices.dropFirst() {
var j = i
while j > 0 && sorted[j - 1].grade < sorted[j].grade {
sorted.swapAt(j - 1, j)
j -= 1
}
}
print(sorted.map(\.name))Show answer and explanation
Answer["Ada", "Cy", "Bo"]
This insertion sort orders by grade, highest first, and only swaps when strictly out of order, so Ada and Cy, both 90, keep their original order: it is stable.
Q1: Swaps equal inversions
Write insertionSortSwaps(_:), returning the number of swaps insertion sort makes,
and check on 100 random arrays that it always equals the number of inversions.
Show solution
func inversions(_ values: [Int]) -> Int {
var count = 0
for i in values.indices {
for j in values.indices where i < j && values[i] > values[j] { count += 1 }
}
return count
}
func insertionSortSwaps(_ values: [Int]) -> Int {
var items = values
var swaps = 0
for i in items.indices.dropFirst() {
var j = i
while j > 0 && items[j - 1] > items[j] {
items.swapAt(j - 1, j)
swaps += 1
j -= 1
}
}
return swaps
}
var generator = SystemRandomNumberGenerator()
for _ in 0..<100 {
let values = (0..<Int.random(in: 0...30, using: &generator)).map { _ in Int.random(in: 0..<20, using: &generator) }
assert(insertionSortSwaps(values) == inversions(values))
}The random arrays include duplicates, which confirm that equal items are never swapped: an equal pair is not an inversion.
Q2: Bottom-up merge sort
Write an iterative merge sort: merge runs of length 1 into runs of 2, then runs of 2 into 4, and so on, with no recursion. Check that it is stable by sorting pairs by their first component only.
Show solution
func mergeSort<T>(_ items: [T], by areInOrder: (T, T) -> Bool) -> [T] {
var source = items
var width = 1
while width < source.count {
var merged: [T] = []
merged.reserveCapacity(source.count)
for start in stride(from: 0, to: source.count, by: 2 * width) {
let middle = min(start + width, source.count)
let end = min(start + 2 * width, source.count)
var i = start, j = middle
while i < middle && j < end {
if areInOrder(source[j], source[i]) { // take from the right only if strictly smaller
merged.append(source[j]); j += 1
} else {
merged.append(source[i]); i += 1
}
}
merged += source[i..<middle]
merged += source[j..<end]
}
source = merged
width *= 2
}
return source
}
let pairs = [(2, "a"), (1, "b"), (2, "c"), (1, "d"), (0, "e")]
let sorted = mergeSort(pairs) { $0.0 < $1.0 }
assert(sorted.map(\.1) == ["e", "b", "d", "a", "c"])
assert(mergeSort([5, 3, 8, 1, 9, 2, 7], by: <) == [1, 2, 3, 5, 7, 8, 9])Taking from the right half only when its item is strictly smaller is what makes the merge stable: on a tie, the left item, which came first, goes first.
Q3: Counting inversions quickly
Counting inversions with two loops is Θ(N²). Count them in Θ(N log N) during a merge sort: when an item from the right half is placed before items still waiting in the left half, it forms an inversion with each of them.
Show solution
func countInversions(_ values: [Int]) -> Int {
func sortAndCount(_ items: ArraySlice<Int>) -> ([Int], Int) {
guard items.count > 1 else { return (Array(items), 0) }
let middle = items.startIndex + items.count / 2
let (left, a) = sortAndCount(items[..<middle])
let (right, b) = sortAndCount(items[middle...])
var merged: [Int] = []
var count = a + b
var i = 0, j = 0
while i < left.count && j < right.count {
if right[j] < left[i] {
merged.append(right[j]); j += 1
count += left.count - i // right[j] precedes every remaining left item
} else {
merged.append(left[i]); i += 1
}
}
merged += left[i...]
merged += right[j...]
return (merged, count)
}
return sortAndCount(values[...]).1
}
assert(countInversions([3, 1, 2]) == 2 && countInversions([4, 3, 2, 1]) == 6 && countInversions([]) == 0)
let big = Array((0..<10_000).reversed())
assert(countInversions(big) == 10_000 * 9_999 / 2)A reversed array of 10,000 items has almost fifty million inversions, counted here without looking at the pairs one by one. The same technique measures how similar two rankings are, for example two people’s preferences in a recommendation system.
Q4 (optional): Nearly sorted
Build an array of 100,000 sorted numbers with 50 random pairs swapped. Count the comparisons made by insertion sort and by merge sort, and explain which does less work.
Show solution
var comparisons = 0
func insertionSort(_ values: [Int]) -> [Int] {
var items = values
for i in items.indices.dropFirst() {
var j = i
while j > 0 {
comparisons += 1
guard items[j - 1] > items[j] else { break }
items.swapAt(j - 1, j)
j -= 1
}
}
return items
}
func mergeSort(_ items: ArraySlice<Int>) -> [Int] {
guard items.count > 1 else { return Array(items) }
let middle = items.startIndex + items.count / 2
let (left, right) = (mergeSort(items[..<middle]), mergeSort(items[middle...]))
var merged: [Int] = [], i = 0, j = 0
while i < left.count && j < right.count {
comparisons += 1
if right[j] < left[i] { merged.append(right[j]); j += 1 } else { merged.append(left[i]); i += 1 }
}
return merged + left[i...] + right[j...]
}
var values = Array(0..<100_000)
var generator = SystemRandomNumberGenerator()
for _ in 0..<50 {
let i = Int.random(in: 0..<(values.count - 5), using: &generator)
values.swapAt(i, i + Int.random(in: 1...5, using: &generator))
}
comparisons = 0
let a = insertionSort(values)
let insertionComparisons = comparisons
comparisons = 0
let b = mergeSort(values[...])
assert(a == b && insertionComparisons < comparisons / 5)Each nearby swap adds only a few inversions, so insertion sort does about N comparisons plus a little. Merge sort still does its full Θ(N log N) work, since it does not notice existing order; it makes fewer comparisons than its maximum here because merges stop early, but several times more than insertion sort. Detecting sorted runs, as Swift’s sort does, gets the best of both.
What’s next
Next lesson: quicksort, which has a bad worst case and is nevertheless often the fastest sort there is.