AlgoScope

More Sorts

Each of these sorts exists because a classic has a weak spot. Insertion sort moves values one slot at a time, so shell sort moves them in strides first and finishes with a gap of one on a nearly sorted array. Quicksort chokes on duplicates, so three-way partitioning gathers every copy of the pivot into a middle zone that is final after one pass. Comparison sorts cannot beat n log n, so bucket sort uses the values themselves to scatter them into ranges and sorts each small bucket. Merge sort ignores order that is already there, so timsort finds the ascending runs in the data, extends short ones with insertion sort, and merges runs instead of single elements. Introsort is what std::sort actually runs: quicksort, but a range of four or fewer values goes to insertion sort, and any stretch that has been partitioned 2 log n times without finishing is handed to heap sort, so bad pivots can slow it down but never make it quadratic. Randomized quicksort takes the other route to a guarantee: choose the pivot at random, and no input can be arranged to be slow on every run. The result compares the same input under thirty seeds, which is what expected running time means: an average over the algorithm's own coin flips, not over inputs.

The player

Bucket sort on 42, 7, 88, 23, 61, 9, 75, 30, 55 with 4 buckets.012345678in0-2425-4950-7475-99out4278823619753055

Sort 9 values between 1 and 99 without comparing them across the whole array. Split the value range into 4 equal buckets, drop each value into the bucket its value falls in, sort each small bucket on its own, then read the buckets out in order.

Check your understanding

The player pauses before each decision in this run and asks what happens next. Here are all 9, with their answers.

  1. Which bucket does 42 fall in?

    • 0-24
    • 25-49
    • 50-74
    • 75-99

    Answer: 25-49. The bucket index is value x 4 / 100, the value's share of the range.

  2. Which bucket does 7 fall in?

    • 0-24
    • 25-49
    • 50-74
    • 75-99

    Answer: 0-24. The bucket index is value x 4 / 100, the value's share of the range.

  3. Which bucket does 88 fall in?

    • 0-24
    • 25-49
    • 50-74
    • 75-99

    Answer: 75-99. The bucket index is value x 4 / 100, the value's share of the range.

  4. Which bucket does 23 fall in?

    • 0-24
    • 25-49
    • 50-74
    • 75-99

    Answer: 0-24. The bucket index is value x 4 / 100, the value's share of the range.

  5. Which bucket does 61 fall in?

    • 0-24
    • 25-49
    • 50-74
    • 75-99

    Answer: 50-74. The bucket index is value x 4 / 100, the value's share of the range.

  6. Which bucket does 9 fall in?

    • 0-24
    • 25-49
    • 50-74
    • 75-99

    Answer: 0-24. The bucket index is value x 4 / 100, the value's share of the range.

  7. Which bucket does 75 fall in?

    • 0-24
    • 25-49
    • 50-74
    • 75-99

    Answer: 75-99. The bucket index is value x 4 / 100, the value's share of the range.

  8. Which bucket does 30 fall in?

    • 0-24
    • 25-49
    • 50-74
    • 75-99

    Answer: 25-49. The bucket index is value x 4 / 100, the value's share of the range.

  9. Which bucket does 55 fall in?

    • 0-24
    • 25-49
    • 50-74
    • 75-99

    Answer: 50-74. The bucket index is value x 4 / 100, the value's share of the range.

How it runs, step by step

  1. Sort 9 values between 1 and 99 without comparing them across the whole array. Split the value range into 4 equal buckets, drop each value into the bucket its value falls in, sort each small bucket on its own, then read the buckets out in order.

    Bucket sort on 42, 7, 88, 23, 61, 9, 75, 30, 55 with 4 buckets.

  2. 42 x 4 / 100 = 1, so 42 goes into bucket 25-49 as its first value.

    42 into bucket 25-49.

  3. 7 x 4 / 100 = 0, so 7 goes into bucket 0-24 as its first value.

    7 into bucket 0-24.

  4. 88 x 4 / 100 = 3, so 88 goes into bucket 75-99 as its first value.

    88 into bucket 75-99.

  5. 23 x 4 / 100 = 0, so 23 goes into bucket 0-24 as its second value.

    23 into bucket 0-24.

  6. 61 x 4 / 100 = 2, so 61 goes into bucket 50-74 as its first value.

    61 into bucket 50-74.

  7. 9 x 4 / 100 = 0, so 9 goes into bucket 0-24 as its third value.

    9 into bucket 0-24.

  8. 75 x 4 / 100 = 3, so 75 goes into bucket 75-99 as its second value.

    75 into bucket 75-99.

  9. 30 x 4 / 100 = 1, so 30 goes into bucket 25-49 as its second value.

    30 into bucket 25-49.

  10. 55 x 4 / 100 = 2, so 55 goes into bucket 50-74 as its second value.

    55 into bucket 50-74.

  11. Bucket 0-24 holds 7, 9, 23: insertion sort puts it in order, 7, 9, 23. A bucket this small costs almost nothing.

    Bucket 0-24 sorted: 7, 9, 23.

  12. Bucket 25-49 holds 30, 42: insertion sort puts it in order, 30, 42. A bucket this small costs almost nothing.

    Bucket 25-49 sorted: 30, 42.

  13. Bucket 50-74 holds 55, 61: insertion sort puts it in order, 55, 61. A bucket this small costs almost nothing.

    Bucket 50-74 sorted: 55, 61.

  14. Bucket 75-99 holds 75, 88: insertion sort puts it in order, 75, 88. A bucket this small costs almost nothing.

    Bucket 75-99 sorted: 75, 88.

  15. Gather bucket 0-24 into output slots 0 to 2: 7, 9, 23. Every value in it is smaller than everything in later buckets, so no comparison across buckets is ever needed.

    Output 7, 9, 23.

  16. Gather bucket 25-49 into output slots 3 to 4: 30, 42. Every value in it is smaller than everything in later buckets, so no comparison across buckets is ever needed.

    Output 30, 42.

  17. Gather bucket 50-74 into output slots 5 to 6: 55, 61. Every value in it is smaller than everything in later buckets, so no comparison across buckets is ever needed.

    Output 55, 61.

  18. Gather bucket 75-99 into output slots 7 to 8: 75, 88. Every value in it is smaller than everything in later buckets, so no comparison across buckets is ever needed.

    Output 75, 88.

  19. Sorted: 7, 9, 23, 30, 42, 55, 61, 75, 88. Scatter and gather are O(n), and sorting the buckets is cheap while values spread evenly across them. When they all land in one bucket the cost falls back to that bucket's insertion sort, O(n^2).

    Sorted after 18 moves.

The code

More Sorts, in Python

def shell_sort(a):
    gap = len(a) // 2
    while gap > 0:                                          # insertion sort with a stride, halving to 1
        for i in range(gap, len(a)):
            j = i
            while j >= gap and a[j - gap] > a[j]:
                swap(a, j - gap, j); j -= gap
        gap //= 2

def quick_sort3(a, lo, hi):                                 # Dijkstra's three-way partition
    if lo >= hi: return
    pivot = a[lo]
    lt = lo; i = lo + 1; gt = hi
    while i <= gt:
        if a[i] < pivot:                                    # grow the < zone
            swap(a, lt, i); lt += 1; i += 1
        elif a[i] > pivot:                                  # grow the > zone; look at the new a[i] next
            swap(a, i, gt); gt -= 1
        else:                                               # equal: it stays in the middle
            i += 1
    quick_sort3(a, lo, lt - 1); quick_sort3(a, gt + 1, hi)  # the equal zone is never touched again

def bucket_sort(a, buckets):
    bucket = [[] for _ in range(buckets)]
    for v in a: bucket[v * buckets // 100].append(v)        # scatter: the value range split evenly
    for b in bucket: b.sort()                               # each bucket is small: insertion sort
    k = 0
    for b in bucket:                                        # gather in bucket order
        for v in b: a[k] = v; k += 1

def tim_sort(a, min_run):
    runs = []
    i = 0
    while i < len(a):
        end = i + 1
        while end < len(a) and a[end - 1] <= a[end]:        # a natural ascending run
            end += 1
        end = max(end, min(i + min_run, len(a)))            # too short: extend it
        insertion_sort(a, i, end - 1); runs.append(range(i, end))
        i = end
    while len(runs) > 1: runs = merge_neighbours(a, runs)   # bottom-up merges, like merge sort

def intro_sort(a):
    sort(a, 0, len(a) - 1, 2 * log2(len(a)))                # the depth budget
def sort(a, lo, hi, depth):
    if hi - lo + 1 <= SMALL:                                # tiny range: insertion sort wins
        insertion_sort(a, lo, hi); return
    if depth == 0:                                          # budget spent: quicksort is degrading
        heap_sort(a, lo, hi); return
    p = partition(a, lo, hi)                                # Lomuto, last value as pivot
    sort(a, lo, p - 1, depth - 1); sort(a, p + 1, hi, depth - 1)

def randomized_quick_sort(a, lo, hi, rng):
    if lo >= hi: return
    swap(a, rng.randint(lo, hi), hi)             # a random pivot moves to the end
    p = partition(a, lo, hi)                     # then the usual Lomuto partition
    randomized_quick_sort(a, lo, p - 1, rng); randomized_quick_sort(a, p + 1, hi, rng)
    # expected depth O(log n) on every input

More Sorts, in JavaScript

function shellSort(a) {
  let gap = Math.floor(a.length / 2);
  while (gap > 0) {                                       // insertion sort with a stride, halving to 1
    for (let i = gap; i < a.length; i++) {
      let j = i;
      while (j >= gap && a[j - gap] > a[j]) { swap(a, j - gap, j); j -= gap; }
    }
    gap = Math.floor(gap / 2);
  }
}

function quickSort3(a, lo, hi) {                          // Dijkstra's three-way partition
  if (lo >= hi) return;
  const pivot = a[lo];
  let lt = lo;
  let i = lo + 1;
  let gt = hi;
  while (i <= gt) {
    if (a[i] < pivot) swap(a, lt++, i++);                 // grow the < zone
    else if (a[i] > pivot) swap(a, i, gt--);              // grow the > zone; look at the new a[i] next
    else i++;                                             // equal: it stays in the middle
  }
  quickSort3(a, lo, lt - 1); quickSort3(a, gt + 1, hi);   // the equal zone is never touched again
}

function bucketSort(a, buckets) {
  const bucket = Array.from({ length: buckets }, () => []);
  for (const v of a) bucket[Math.floor((v * buckets) / 100)].push(v);   // scatter: the value range split evenly
  for (const b of bucket) b.sort((x, y) => x - y);                      // each bucket is small: insertion sort
  let k = 0;
  for (const b of bucket) for (const v of b) a[k++] = v;                // gather in bucket order
}

function timSort(a, minRun) {
  let runs = [];
  let i = 0;
  while (i < a.length) {
    let end = i + 1;
    while (end < a.length && a[end - 1] <= a[end]) end++;   // a natural ascending run
    end = Math.max(end, Math.min(i + minRun, a.length));    // too short: extend it
    insertionSort(a, i, end - 1); runs.push([i, end]);
    i = end;
  }
  while (runs.length > 1) runs = mergeNeighbours(a, runs);  // bottom-up merges, like merge sort
}

const introSort = (a) => sort(a, 0, a.length - 1, 2 * log2(a.length));  // the depth budget
function sort(a, lo, hi, depth) {
  if (hi - lo + 1 <= SMALL) { insertionSort(a, lo, hi); return; }       // tiny range: insertion sort wins
  if (depth === 0) { heapSort(a, lo, hi); return; }                     // budget spent: quicksort is degrading
  const p = partition(a, lo, hi);                                       // Lomuto, last value as pivot
  sort(a, lo, p - 1, depth - 1); sort(a, p + 1, hi, depth - 1);
}

function randomizedQuickSort(a, lo, hi, rng) {
  if (lo >= hi) return;
  swap(a, rng.nextInt(lo, hi + 1), hi);           // a random pivot moves to the end
  const p = partition(a, lo, hi);                 // then the usual Lomuto partition
  randomizedQuickSort(a, lo, p - 1, rng); randomizedQuickSort(a, p + 1, hi, rng);
}                                                 // expected depth O(log n) on every input

More Sorts, in Kotlin

fun shellSort(a: IntArray) {
    var gap = a.size / 2
    while (gap > 0) {                                        // insertion sort with a stride, halving to 1
        for (i in gap until a.size) {
            var j = i
            while (j >= gap && a[j - gap] > a[j]) { swap(a, j - gap, j); j -= gap }
        }
        gap /= 2
    }
}

fun quickSort3(a: IntArray, lo: Int, hi: Int) {             // Dijkstra's three-way partition
    if (lo >= hi) return
    val pivot = a[lo]
    var lt = lo; var i = lo + 1; var gt = hi
    while (i <= gt) {
        when {
            a[i] < pivot -> swap(a, lt++, i++)                 // grow the < zone
            a[i] > pivot -> swap(a, i, gt--)                   // grow the > zone; look at the new a[i] next
            else -> i++                                        // equal: it stays in the middle
        }
    }
    quickSort3(a, lo, lt - 1); quickSort3(a, gt + 1, hi)     // the equal zone is never touched again
}

fun bucketSort(a: IntArray, buckets: Int) {
    val bucket = List(buckets) { mutableListOf<Int>() }
    for (v in a) bucket[v * buckets / 100] += v               // scatter: the value range split evenly
    for (b in bucket) b.sort()                                // each bucket is small: insertion sort
    var k = 0
    for (b in bucket) for (v in b) a[k++] = v                 // gather in bucket order
}

fun timSort(a: IntArray, minRun: Int) {
    var runs = mutableListOf<IntRange>()
    var i = 0
    while (i < a.size) {
        var end = i + 1
        while (end < a.size && a[end - 1] <= a[end]) end++    // a natural ascending run
        end = max(end, min(i + minRun, a.size))              // too short: extend it
        insertionSort(a, i, end - 1); runs += i until end
        i = end
    }
    while (runs.size > 1) runs = mergeNeighbours(a, runs)    // bottom-up merges, like merge sort
}

fun introSort(a: IntArray) = sort(a, 0, a.size - 1, 2 * log2(a.size))   // the depth budget
fun sort(a: IntArray, lo: Int, hi: Int, depth: Int) {
    if (hi - lo + 1 <= SMALL) { insertionSort(a, lo, hi); return }   // tiny range: insertion sort wins
    if (depth == 0) { heapSort(a, lo, hi); return }                   // budget spent: quicksort is degrading
    val p = partition(a, lo, hi)                                      // Lomuto, last value as pivot
    sort(a, lo, p - 1, depth - 1); sort(a, p + 1, hi, depth - 1)
}

fun randomizedQuickSort(a: IntArray, lo: Int, hi: Int, rng: Random) {
    if (lo >= hi) return
    swap(a, rng.nextInt(lo, hi + 1), hi)             // a random pivot moves to the end
    val p = partition(a, lo, hi)                     // then the usual Lomuto partition
    randomizedQuickSort(a, lo, p - 1, rng); randomizedQuickSort(a, p + 1, hi, rng)
}                                                    // expected depth O(log n) on every input

Write it yourself

Define threeWayQuickSort(values) and return the same values in ascending order. It runs in your browser against this lesson's own 2 examples.

// Partition into less than, equal to and greater than the pivot, so runs of duplicates are finished in one pass.function threeWayQuickSort(values) { return values;}
6 linesTab indents. Escape, then Tab, leaves the editor. Ctrl-Enter runs (Cmd-Enter on a Mac).

    Remember

    • Shell sort: insertion sort with gaps n/2, n/4, ..., 1. The big gaps move values far cheaply.
    • Three-way quicksort: zones smaller, equal, larger. The equal zone is final, so duplicates cost O(n).
    • Bucket sort is linear on evenly spread data. Timsort merges natural runs, O(n) on sorted input. Introsort is quicksort with insertion sort under 5 values and heap sort once 2 log n partitions have not finished.

    Where this is used

    std::sort is introsortStandard libraries

    Since C++11 the standard has required O(n log n) worst case from std::sort, which plain quicksort cannot promise, and libstdc++ meets it with introsort. Its constants are worth seeing next to the visualization: median-of-three pivots rather than a fixed position, the heap sort fallback at depth 2 log2 n, and a threshold of 16 rather than 4, below which it does not recurse at all - it leaves those stretches alone and cleans the whole array up with one insertion sort pass at the end, which is cheaper than many small ones. Quicksort stays the main engine because it partitions in place and walks memory sequentially. Heap sort is reached only on input that was already defeating it.

    Timsort in JavaScript enginesLanguage runtimes

    V8 replaced its quicksort for Array.prototype.sort with Timsort in V8 7.0 and Chrome 70, in 2018, and ES2019 then made stability part of the language, which a quicksort cannot provide: sorting a table by one column and then by another has to leave the first order intact inside ties. Run detection is the second payoff, because web data rarely arrives shuffled - arrays built by appending, filtered out of an already sorted list, or re-sorted after a single edit are mostly ordered already, and those are the shapes V8's own benchmarks improved on most.

    Range partitioning in distributed sortsData

    Spark's RangePartitioner and Hadoop's TeraSort sort a dataset larger than one machine by choosing boundary keys, shipping each record to the partition whose range covers it, and sorting each partition locally. That is bucket sort with the scatter step turned into a network shuffle, and the payoff is the same: because the buckets are ordered, concatenating the results needs no final merge across machines. The boundaries come from sampling the data rather than cutting the key range into equal slices, since even spread is the one assumption real input does not honour.

    Random pivots as a denial-of-service defenceSecurity

    A deterministic quicksort picks its pivot by a fixed rule, so anyone who knows the rule can construct the input that drives it quadratic. McIlroy showed in 1999 that an adversarial comparison function can do this to such an implementation without even knowing the values being sorted. A sort behind a public endpoint then becomes a way to burn CPU with a small request. Drawing the pivot from a random source forces the attacker to guess the seed instead, which is why production sorts either randomise or, like introsort, cap the damage with a depth limit.

    Why it works this way

    Why halving the gap is the worst of the common gap sequences

    The last pass of shell sort is a plain insertion sort, so the result is correct whatever gaps came before. The earlier passes exist only to remove distant inversions cheaply so that final pass has almost nothing left to move. That is also why the halving sequence is a poor choice: when n is a power of two every gap except the last is even, so a value at an odd index is never compared with one at an even index until the gap reaches 1, and the worst case stays quadratic. Hibbard's 2^k - 1 removes that by making the gaps odd and gets Theta(n^1.5). Ciura's 1, 4, 10, 23, 57, 132, 301, 701 is the fastest known in practice and was found by search rather than proof. No optimal sequence is known.

    In the three-way partition, why i does not move when a[i] > pivot

    The value swapped in from position gt arrived from the unexamined right end, so the loop has to look at it on the next turn. That is why the greater branch moves gt and leaves i alone. The less branch can advance both counters because a[lt] is either the pivot itself or a value already known to equal it, so that swap places a known value rather than skipping an unknown one. Advancing i in the greater branch is the standard bug here, and it is quiet: unexamined values end up inside the equal zone, which the recursion never visits again.

    Timsort's run stack is the correctness argument, not bookkeeping

    Timsort does not merge a run as soon as it finds one. It pushes run lengths on a stack and merges only while the top entries break the invariants X > Y + Z and Y > Z, which keep merges roughly balanced and so bound both the total merge cost and how deep the stack can get - which is why the stack can be a small fixed-size array. A 2015 attempt to verify java.util.TimSort formally found the collapse check did not actually restore that invariant, and OpenJDK issue JDK-8072909 is the resulting crash: an array of about 67 million elements overruns the stack and throws ArrayIndexOutOfBoundsException. OpenJDK both enlarged the stack, to 49 entries from 119151 elements up, and tightened mergeCollapse to test four runs rather than three. CPython repaired its own check and then in 3.11 dropped this rule entirely for the powersort merge policy, which chooses the merge order from the run lengths and is provably near-optimal, so listsort.txt now describes powersort rather than the invariants above.

    Why introsort falls back to heap sort rather than merge sort

    Merge sort would cap the worst case just as well, but it needs a buffer, and std::sort is expected to sort in place without allocating. Heap sort is the common O(n log n) sort that runs in O(1) extra space, and its weakness - jumping around memory, so poor cache behaviour - barely matters because it only ever runs on the stretches where quicksort was already failing. The depth budget is loose for the same reason: a healthy quicksort recursion is about log2 n deep, so 2 log2 n almost never fires on ordinary input and the guarantee is effectively free.

    Read more

    Next up

    Skip List

    Layered linked lists where higher levels skip ahead, giving expected O(log n) search.

    Next lesson: Skip List