Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Merge Sort, Quicksort & Heapsort

Three ways to sort in O(n log n) by comparing elements.

Three algorithms sort nn items with about nlog⁡2nn \log_2 n comparisons, and each one wins somewhere. Merge sort is stable and never has a bad day, quicksort is usually the fastest in practice, and heapsort needs no extra memory and has no bad inputs at all. No comparison sort can do asymptotically better, so what separates them is everything else: memory, stability, cache behavior and the worst case.

What you’ll learn

  • Analyze insertion sort through inversions: Θ(n+I)\Theta(n + I) time, so Θ(n)\Theta(n) on sorted input and Θ(n2)\Theta(n^2) in the worst and average cases.
  • Implement merge sort, solve its recurrence exactly, and count inversions as a by-product.
  • Implement quicksort with a Lomuto partition, prove its expected 2(n+1)Hn−4n2(n+1)H_n - 4n comparisons, and explain its Θ(n2)\Theta(n^2) worst case and Hoare's alternative.
  • Build a heap in O(n)O(n) time and sort with it in O(nlog⁡n)O(n \log n) worst-case time and O(1)O(1) extra space.
  • Use library sorts correctly: keys and comparators, stable versus unstable sorts, and strict weak orderings.

The baseline: insertion sort and inversions

Every fast sort is measured against the obvious one. Insertion sort keeps a sorted prefix and inserts the next element into it by shifting larger elements one slot right. Its loop invariant: before iteration jj, the prefix a[0..j−1]a[0..j-1] holds the first jj input elements in sorted order.

The right measure of its work is the number of inversions II: the pairs i<ji < j with a[i]>a[j]a[i] > a[j]. A sorted array has none, a reversed one all (n2)\binom{n}{2}.

python
def insertion_sort(a):
    for j in range(1, len(a)):
        key, i = a[j], j - 1
        while i >= 0 and a[i] > key:   # invariant: a[0..j-1] is sorted
            a[i + 1] = a[i]            # each shift removes exactly one inversion
            i -= 1
        a[i + 1] = key

Sorts in place and is stable: the strict > never moves a key past an equal one.

DerivationInsertion sort costs Θ(n + I)
  1. shifts=I\text{shifts} = I

    Shifts. A shift moves the key past one larger element to its left, so it removes exactly one inversion, and nothing else changes the order. The loop ends with the array sorted, so the number of shifts is exactly the number of inversions:

  2. I  ≤  C  ≤  I+(n−1)I \;\le\; C \;\le\; I + (n - 1)

    Comparisons. Every comparison either causes a shift or ends the inner loop, and each of the n−1n - 1 inner loops ends at most once by a failed comparison:

  3. Imax⁡=(n2)=n(n−1)2,E[I]=12(n2)=n(n−1)4I_{\max} = \binom{n}{2} = \frac{n(n-1)}{2}, \qquad \E[I] = \frac12\binom{n}{2} = \frac{n(n-1)}{4}

    Worst and average cases. Reversed input has all (n2)\binom{n}{2} pairs inverted. In a uniformly random permutation each pair is inverted with probability 12\tfrac12, so by linearity of expectation:

  4. T(n)=Θ(n+I)T(n) = \Theta(n + I)

    So insertion sort takes Θ(n+I)\Theta(n + I) time: Θ(n)\Theta(n) on sorted input, Θ(n2)\Theta(n^2) in the worst and average cases, and O(nk)O(nk) when every element starts at most kk places from its final position, because then two elements can be inverted only if they start fewer than 2k2k places apart, so each element is inverted with fewer than 2k2k elements to its right. It is an adaptive sort.

Predict before you look

How many shifts does insertion sort make on [3,1,4,1,5,9,2,6][3, 1, 4, 1, 5, 9, 2, 6]?

Show the answer

8

Count the inversions. 3 precedes three smaller keys (1, 1, 2); 4 precedes 1 and 2; 5 precedes 2; 9 precedes 2 and 6. That is 3+2+1+2=83 + 2 + 1 + 2 = 8. The two 1s are equal, so they form no inversion, and the strict comparison never shifts one past the other.

Merge sort: a recurrence you can solve exactly

Merge sort is divide and conquer in its purest form: split the array into halves, sort each recursively, and merge the two sorted runs by repeatedly taking the smaller front element. Taking from the left run on ties keeps it a stable sort. The merge also sees, for free, how many elements of the left run each right element jumps over, which is exactly the number of inversions between the halves:

python
def sort_count(a):
    """Return (sorted copy of a, number of inversions in a)."""
    n = len(a)
    if n <= 1:
        return a[:], 0
    left, x = sort_count(a[:n // 2])
    right, y = sort_count(a[n // 2:])
    out, inv, i, j = [], x + y, 0, 0
    while i < len(left) and j < len(right):
        if right[j] < left[i]:          # strict: on ties the left run goes first (stable)
            out.append(right[j]); j += 1
            inv += len(left) - i        # right[j] jumps over everything left in `left`
        else:
            out.append(left[i]); i += 1
    out += left[i:] + right[j:]
    return out, inv

sort_count([3, 1, 2]) returns ([1, 2, 3], 2). Tested against a brute-force inversion count on thousands of random arrays. The inversion count measures how far one ranking is from another (the Kendall tau distance).

DerivationMerge sort’s worst case, exactly
  1. W(n)=W(⌈n/2⌉)+W(⌊n/2⌋)+n−1,W(1)=0W(n) = W(\lceil n/2 \rceil) + W(\lfloor n/2 \rfloor) + n - 1, \qquad W(1) = 0

    Recurrence. Each comparison of a merge outputs one element, and the last element needs no comparison, so merging nn elements costs at most n−1n - 1 comparisons. With W(n)W(n) the worst-case count:

  2. W(2k)2k=W(2k−1)2k−1+1−2−k=∑j=1k(1−2−j)=k−1+2−k\frac{W(2^k)}{2^k} = \frac{W(2^{k-1})}{2^{k-1}} + 1 - 2^{-k} = \sum_{j=1}^{k} \left(1 - 2^{-j}\right) = k - 1 + 2^{-k}

    Powers of two. For n=2kn = 2^k, divide by nn and unroll; each level adds 1−2−j1 - 2^{-j}:

  3. W(n)=n⌈log⁡2n⌉−2⌈log⁡2n⌉+1  ≤  nlog⁡2nW(n) = n \lceil \log_2 n \rceil - 2^{\lceil \log_2 n \rceil} + 1 \;\le\; n \log_2 n

    So W(n)=nlog⁡2n−n+1W(n) = n \log_2 n - n + 1 when nn is a power of 2, and by induction for every nn (checked against the recurrence for all nn up to 5000):

  4. I(a)=I(left)+I(right)+#{ (x,y):x∈left, y∈right, x>y }I(a) = I(\text{left}) + I(\text{right}) + \#\{\,(x, y) : x \in \text{left},\ y \in \text{right},\ x > y\,\}

    Cost. That is 49 comparisons for n=16n = 16 and 8,977 for n=1000n = 1000. Every level of the recursion also copies all nn elements through a buffer, so merge sort takes Θ(nlog⁡n)\Theta(n \log n) time on every input, with Θ(n)\Theta(n) extra space. Inversions split into those inside the left half, inside the right half, and across, and the merge counts the third kind exactly, so counting adds only O(1)O(1) per output element:

Think first Merge sort's comparison count on 16 keys is at most 49. In the widget it makes 32 comparisons on sorted and on reversed input. Why exactly 32 in both cases?

When every key of one run is smaller than every key of the other, the merge compares each key of the smaller-keyed run once, then copies the other run without comparing: mm comparisons for two runs of length mm. On sorted input the left run always runs out first, on reversed input the right run does. Each of the 4 levels merges pairs of equal runs whose sizes add up to 16, so it makes 8 comparisons, and 4×8=324 \times 8 = 32. Merge sort is not adaptive in time, though: it still copies every element at every level.

Quicksort: partition, then recurse

Quicksort (Hoare, 1961) does its work before recursing. A partition step picks a pivot and rearranges a[lo..hi]a[lo..hi] so that the keys ≤\le pivot come first, then the pivot, then the larger keys. The pivot now sits at its final index pp, and the two sides are sorted independently. Nothing needs merging, and everything happens in place.

The partition below is Lomuto's, the version in CLRS and in the widget. Its invariant: a[lo..i−1]≤a[lo..i-1] \le pivot <a[i..j−1]< a[i..j-1], while a[j..hi−1]a[j..hi-1] is not yet examined.

python
import random

def quicksort(a, lo=0, hi=None):
    if hi is None:
        hi = len(a) - 1
    while lo < hi:
        p = partition(a, lo, hi)
        if p - lo < hi - p:             # recurse on the smaller side, loop on the larger,
            quicksort(a, lo, p - 1)     # so the call stack stays O(log n) deep
            lo = p + 1
        else:
            quicksort(a, p + 1, hi)
            hi = p - 1

def partition(a, lo, hi):               # Lomuto, with a uniformly random pivot
    r = random.randint(lo, hi)
    a[r], a[hi] = a[hi], a[r]
    pivot, i = a[hi], lo
    for j in range(lo, hi):             # invariant: a[lo..i-1] <= pivot < a[i..j-1]
        if a[j] <= pivot:
            a[i], a[j] = a[j], a[i]
            i += 1
    a[i], a[hi] = a[hi], a[i]           # the pivot lands at its final index
    return i

Tested on thousands of random arrays, many with repeated keys. Each recursive call gets at most half of the range, so the stack never exceeds log⁡2n\log_2 n frames, even when the pivots are bad; the time can still be quadratic.

DerivationProof with indicator variables
  1. Cn=∑i<jXij,E[Cn]=∑i<jPr⁡[ zi and zj are compared ]C_n = \sum_{i<j} X_{ij}, \qquad \E[C_n] = \sum_{i<j} \Pr[\,z_i \text{ and } z_j \text{ are compared}\,]

    Each pair is compared at most once. Name the keys by rank, z1<z2<⋯<znz_1 < z_2 < \dots < z_n. Every comparison is between the current pivot and another key of its range, and after its partition the pivot is never touched again. With Xij=1X_{ij} = 1 when ziz_i and zjz_j are ever compared:

  2. Pr⁡[ zi and zj are compared ]=2j−i+1\Pr[\,z_i \text{ and } z_j \text{ are compared}\,] = \frac{2}{j - i + 1}

    When they meet. Until some pivot is drawn from {zi,…,zj}\{z_i, \dots, z_j\}, all of these keys stay in one range. If that first pivot is ziz_i or zjz_j, the two are compared; if it lies strictly between them, they land on different sides and never meet. Each of the j−i+1j - i + 1 keys is equally likely to be drawn first:

  3. E[Cn]=∑k=2n2(n−k+1)k=2(n+1)(Hn−1)−2(n−1)=2(n+1)Hn−4n\E[C_n] = \sum_{k=2}^{n} \frac{2(n - k + 1)}{k} = 2(n+1)(H_n - 1) - 2(n - 1) = 2(n+1)H_n - 4n

    Sum. Group the pairs by k=j−i+1k = j - i + 1; there are n−k+1n - k + 1 pairs for each kk:

  4. 2ln⁡2≈1.3862 \ln 2 \approx 1.386

    Size. With Hn=ln⁡n+γ+O(1/n)H_n = \ln n + \gamma + O(1/n), the leading term is 2nln⁡n=(2ln⁡2) nlog⁡2n2n \ln n = (2 \ln 2)\, n \log_2 n. The approach to that constant is slow, because of the −2.85n-2.85n term: E[Cn]/(nlog⁡2n)\E[C_n] / (n \log_2 n) is about 1.10 at n=103n = 10^3 and 1.24 at n=106n = 10^6.

Check your understanding

Randomized quicksort sorts the keys 1,2,…,1001, 2, \dots, 100. What is the probability that the keys 1 and 100 are ever compared with each other?

  1. 1100\tfrac{1}{100}
  2. 299\tfrac{2}{99}
  3. 150\tfrac{1}{50}
  4. 1, since the first pivot is compared with every key
Show the answer

C. 150\tfrac{1}{50}

They are compared only if the first pivot drawn from {1,…,100}\{1, \dots, 100\}, which here is the very first pivot of the whole sort, is 1 or 100: probability 2/100=1/502/100 = 1/50. Any other first pivot sends them to different sides for good. Neighbors in sorted order, such as 40 and 41, are always compared.

Heapsort, and the three side by side

Heapsort (Williams, 1964) keeps a max-heap inside the array itself: the children of index ii are 2i+12i + 1 and 2i+22i + 2, and every parent is at least as large as its children (the heap property). Build the heap, then repeat: swap the root, which is the maximum, to the end of the heap region, shrink the region by one, and sift down the new root.

python
def heapsort(a):
    n = len(a)
    def sift_down(i, size):             # restore the max-heap property below index i
        while True:
            big, l, r = i, 2 * i + 1, 2 * i + 2
            if l < size and a[l] > a[big]: big = l
            if r < size and a[r] > a[big]: big = r
            if big == i:
                return
            a[i], a[big] = a[big], a[i]
            i = big
    for i in range(n // 2 - 1, -1, -1): # Floyd's bottom-up construction: O(n)
        sift_down(i, n)
    for end in range(n - 1, 0, -1):     # move the maximum behind the shrinking heap
        a[0], a[end] = a[end], a[0]
        sift_down(0, end)

In place and tested like the others. The same sift-down serves both phases; only the heap's size changes.

DerivationHeapsort’s cost
  1. ∑h≥0h⋅n2h+1  =  n∑h≥0h2h+1  =  n levels, so at most about 2n comparisons\sum_{h \ge 0} h \cdot \frac{n}{2^{h+1}} \;=\; n \sum_{h \ge 0} \frac{h}{2^{h+1}} \;=\; n \text{ levels, so at most about } 2n \text{ comparisons}

    Building is linear. Floyd's construction (1964) sifts down the nodes from index ⌊n/2⌋−1\lfloor n/2 \rfloor - 1 back to 0, the bottom-up heapify. A node of height hh sinks at most hh levels, with 2 comparisons per level, and only about n/2h+1n / 2^{h+1} nodes have height hh:

  2. Cheapsort  ≤  2n+2(n−1)⌊log⁡2n⌋  =  O(nlog⁡n) on every inputC_{\text{heapsort}} \;\le\; 2n + 2(n - 1)\lfloor \log_2 n \rfloor \;=\; O(n \log n) \text{ on every input}

    Extracting is logarithmic. Each of the n−1n - 1 extractions sifts a root down a heap of height at most ⌊log⁡2n⌋\lfloor \log_2 n \rfloor. (For the build alone: on 1,000 keys in increasing order, where every key sinks to the bottom, the code above makes 1,982 comparisons, under 2n2n.)

  3. In place, not stable, not cache-friendly. Heapsort needs O(1)O(1) extra memory on every input. Its swaps carry keys over long distances, past equal keys, so it is not stable, and its jumps from ii to 2i+12i + 1 touch memory far apart, which caches dislike. Heapsort is the guarantee, rarely the fastest choice.

AlgorithmComparisons, worst caseComparisons, typicalExtra spaceStableNotes
Insertion sort(n2)\binom{n}{2}≈n2/4\approx n^2/4 random; n−1n - 1 sortedO(1)O(1)yesadaptive, Θ(n+I)\Theta(n + I); best for tiny or nearly sorted ranges
Merge sortn⌈log⁡2n⌉−2⌈log⁡2n⌉+1n \lceil \log_2 n \rceil - 2^{\lceil \log_2 n \rceil} + 1between 12nlog⁡2n\tfrac12 n \log_2 n and the worst caseΘ(n)\Theta(n)yessequential scans; the core of Timsort and of external sorting
Quicksort, random pivot(n2)\binom{n}{2}≈1.39 nlog⁡2n\approx 1.39\, n \log_2 n expectedO(log⁡n)O(\log n) stacknoin place, sequential scans, usually fastest
Heapsort≈2nlog⁡2n\approx 2n \log_2 na little lessO(1)O(1)noguaranteed and in place; scattered memory access
Libraries combine them. Introsort runs quicksort, falls back to heapsort when the recursion gets too deep, and finishes small ranges with insertion sort; Timsort merges sorted runs it finds in the data and extends short runs with insertion sort.

Recognizing it

In practice you rarely write a sort; you decide to sort, and call the library. Sorting first is the right move when order turns a hard question into a local one:

  • A greedy choice needs an order: intervals by end time, jobs by deadline or by length.
  • Events happen at times: sort the starts and ends, then sweep once (sweep line).
  • Pairs, gaps or nearest values: sort, then use two pointers or look at neighbors.
  • Many queries on fixed data: sort once, then binary search each query.
  • Constraints around n≤105n \le 10^5 to 10610^6 allow an O(nlog⁡n)O(n \log n) preprocessing step, under the rule of thumb of 10810^8 simple steps per second.
Problem, in briefKey ideaCost
Merge overlapping intervalssort by start; extend the current interval while the next one starts before it endsO(nlog⁡n)O(n \log n)
The most meetings in progress at oncesort the 2n2n start and end events, ends first on ties; sweep with a counterO(nlog⁡n)O(n \log n)
How far one ranking is from anothercount inversions with merge sortO(nlog⁡n)O(n \log n)
Arrange numbers so that their concatenation is largestsort with the comparator "xx before yy iff xy>yxxy > yx"O(nlog⁡n)O(n \log n) string comparisons
Order jobs to minimize the total waiting timeshortest job first, proved by an exchange argumentO(nlog⁡n)O(n \log n)
The comparator of the fourth row is transitive, which is not obvious and is exactly what makes sorting by it correct.
python
from functools import cmp_to_key

people = [("Lee", "Ana", 31), ("Kim", "Ben", 25), ("Lee", "Cal", 25), ("Kim", "Dee", 40)]
print(sorted(people, key=lambda p: (-p[2], p[0])))  # oldest first, ties by last name
print(sorted(people, key=lambda p: p[0]))           # stable: ties keep their order

def largest_concatenation(nums):
    """Arrange non-negative integers so that their concatenation is as large as possible."""
    def order(x, y):                                # x goes first if xy > yx
        return (x + y < y + x) - (x + y > y + x)
    s = ''.join(sorted(map(str, nums), key=cmp_to_key(order)))
    return '0' if s[0] == '0' else s

print(largest_concatenation([3, 30, 34, 5, 9]))     # 9534330

Python's sorted and list.sort are Timsort, guaranteed stable. A key tuple sorts by several keys at once, and negating a number reverses its order. Checked against brute force over all permutations.

cpp
#include <algorithm>
#include <cstdio>
#include <string>
#include <tuple>
#include <vector>

struct Person { std::string last, first; int age; };

int main() {
    std::vector<Person> v = {{"Lee", "Ana", 31}, {"Kim", "Ben", 25}, {"Lee", "Cal", 25}, {"Kim", "Dee", 40}};
    // Oldest first, ties by last name: compare tuples, a strict weak ordering.
    std::sort(v.begin(), v.end(), [](const Person& a, const Person& b) {
        return std::tie(b.age, a.last) < std::tie(a.age, b.last);
    });
    // Group by last name, keeping the age order inside each group.
    std::stable_sort(v.begin(), v.end(), [](const Person& a, const Person& b) { return a.last < b.last; });
    for (const auto& p : v) std::printf("%s %s %d\n", p.first.c_str(), p.last.c_str(), p.age);
    // Prints: Dee Kim 40, Ben Kim 25, Ana Lee 31, Cal Lee 25 (one per line).
    // Never: [](int x, int y) { return x <= y; }. Not a strict weak ordering: undefined behavior.
}

C++17. std::sort is not stable and, since C++11, must make O(nlog⁡n)O(n \log n) comparisons in the worst case (implementations typically use introsort). std::stable_sort takes O(nlog⁡n)O(n \log n) with a spare buffer and O(nlog⁡2n)O(n \log^2 n) without one.

Common bugs.

  • A comparator that is not a strict weak ordering: <=, comparisons with NaN, random or inconsistent answers. In C++ the behavior is undefined and can read out of bounds; Java's Timsort may throw "Comparison method violates its general contract!"; Python returns a meaningless order.
  • Comparing by subtraction: return a - b; in Java or C overflows when aa and bb are large with opposite signs. Use Integer.compare(a, b) or compare with <.
  • Losing stability: sorting by a secondary key and then by the primary key with an unstable sort scrambles the secondary order.
  • Recursion depth: a recursive quicksort with a fixed pivot rule recurses nn deep on sorted input, far past Python's default recursion limit of 1,000.
  • Numbers as strings: "10" < "9" is true. And a.sort() returns None; sorted(a) returns a new list.
Check your understanding

You get n≤2×105n \le 2 \times 10^5 meetings as half-open time intervals [s,e)[s, e) and must report the largest number of meetings in progress at the same moment. Which approach fits?

  1. Compare every pair of meetings and count the overlapping pairs
  2. Sort the 2n2n start and end events by time, ends before starts on ties, and sweep with a counter that adds 1 at a start and subtracts 1 at an end, tracking its maximum
  3. Sort the meetings by length and greedily pick the shortest ones
  4. Binary search over the start times
Show the answer

B. Sort the 2n2n start and end events by time, ends before starts on ties, and sweep with a counter that adds 1 at a start and subtracts 1 at an end, tracking its maximum

The number of meetings in progress changes only at events, so one sweep over the sorted events sees every candidate moment: O(nlog⁡n)O(n \log n) in all. Processing ends before starts on ties means a meeting ending at 10 and one starting at 10 do not overlap, as half-open intervals require.

Key takeaways

  • Insertion sort costs Θ(n+I)\Theta(n + I) with II inversions: linear on nearly sorted input, quadratic on average, and every sort that only swaps neighbors is quadratic on average.
  • Merge sort makes at most n⌈log⁡2n⌉−2⌈log⁡2n⌉+1n \lceil \log_2 n \rceil - 2^{\lceil \log_2 n \rceil} + 1 comparisons, is stable, needs Θ(n)\Theta(n) extra space, and counts inversions as a by-product.
  • Randomized quicksort makes 2(n+1)Hn−4n≈1.39 nlog⁡2n2(n+1)H_n - 4n \approx 1.39\, n \log_2 n expected comparisons on every input and works in place, but it is Θ(n2)\Theta(n^2) in the worst case and not stable.
  • Heapsort builds a heap in O(n)O(n) and sorts in Θ(nlog⁡n)\Theta(n \log n) worst-case time with O(1)O(1) extra space, at the price of more comparisons and poor locality.
  • Use the library sort: a stable sort or a key tuple for several keys, and a comparator that is a strict weak ordering.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Insertion sort runs on an array of nn keys in which every key is at most 3 positions away from its sorted position. What is its running time?

  1. Θ(n2)\Theta(n^2), like any insertion sort
  2. Θ(nlog⁡n)\Theta(n \log n)
  3. O(n)O(n)
  4. O(nlog⁡3)O(n \log 3), which is not linear
Show the answer

C. O(n)O(n)

Two keys can be inverted only if they start fewer than 2⋅32 \cdot 3 positions apart, so there are fewer than 6n6n inversions, and insertion sort takes Θ(n+I)=O(n)\Theta(n + I) = O(n) time. This is why hybrid sorts finish nearly sorted pieces with insertion sort.

Question 2

An adversary picks the input to your quicksort, which chooses each pivot uniformly at random. Which statement is true?

  1. The expected number of comparisons is 2(n+1)Hn−4n2(n+1)H_n - 4n on every input; the expectation is over the pivots, not the input
  2. The worst-case running time is O(nlog⁡n)O(n \log n)
  3. The adversary can choose an input that makes the expected time Θ(n2)\Theta(n^2)
  4. The expected time is O(nlog⁡n)O(n \log n) only on random inputs
Show the answer

A. The expected number of comparisons is 2(n+1)Hn−4n2(n+1)H_n - 4n on every input; the expectation is over the pivots, not the input

The proof that pairs zi,zjz_i, z_j are compared with probability 2/(j−i+1)2/(j - i + 1) uses only the randomness of the pivots, so it holds for every input. Unlucky pivots can still cost Θ(n2)\Theta(n^2), but with tiny probability; no input is bad in expectation.

Question 3

Why does bottom-up heap construction take O(n)O(n) time, even though it calls sift-down about n/2n/2 times and a sift-down can take log⁡2n\log_2 n steps?

  1. Most nodes are near the bottom: a node of height hh sifts down at most hh levels, and only about n/2h+1n/2^{h+1} nodes have height hh, so the total is ∑hh n/2h+1=n\sum_h h\,n/2^{h+1} = n levels
  2. Sift-down takes O(1)O(1) time on average
  3. It actually takes Θ(nlog⁡n)\Theta(n \log n) time in the worst case
  4. The input is usually nearly sorted
Show the answer

A. Most nodes are near the bottom: a node of height hh sifts down at most hh levels, and only about n/2h+1n/2^{h+1} nodes have height hh, so the total is ∑hh n/2h+1=n\sum_h h\,n/2^{h+1} = n levels

Half the nodes are leaves and do nothing, a quarter sift down at most one level, an eighth at most two, and so on. The weighted sum converges: at most nn levels and 2n2n comparisons in all, whatever the input.

Question 4

You must sort 10810^8 records in memory with almost no extra space and a guaranteed O(nlog⁡n)O(n \log n) worst case; stability does not matter. Which algorithm fits?

  1. Merge sort
  2. Quicksort with random pivots
  3. Insertion sort
  4. Heapsort
Show the answer

D. Heapsort

Heapsort works in place with O(1)O(1) extra space and makes at most about 2nlog⁡2n2n \log_2 n comparisons on every input. Introsort, which runs quicksort and falls back to heapsort, offers the same guarantee and is faster in practice.

Question 5

A C++ program calls std::sort(v.begin(), v.end(), [](int a, int b) { return a <= b; }) and crashes on some inputs with many equal values. Why?

  1. std::sort is not stable
  2. The comparator is not a strict weak ordering, since it says aa comes before aa, so the behavior is undefined and an unguarded scan can run past the end of the range
  3. Lambdas cannot be passed to std::sort
  4. Comparing ints with <= overflows
Show the answer

B. The comparator is not a strict weak ordering, since it says aa comes before aa, so the behavior is undefined and an unguarded scan can run past the end of the range

std::sort requires comp(a, a) to be false, together with transitivity of the order and of equivalence. Implementations rely on this, for example by scanning for an element not less than the pivot without a bounds check. Use < instead.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 2, 6 and 7.
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), chapter 2.
  • C. A. R. Hoare, "Quicksort," The Computer Journal 5(1) (1962), 10–16.
  • J. W. J. Williams, "Algorithm 232: Heapsort," Communications of the ACM 7(6) (1964).