Skip to content

Randomised quick sort

ordering

Level 3 of 3

Also called Randomised quicksort.

how it works

The idea in a few sentences and two pictures, then one row sorted step by step.

Randomised quick sort is quick sort with one change: the pivot is picked at random from the part, every place as likely. The pivot is swapped to the end of the part, out of the way. Then the part is split as quick sort splits it: each smaller number swaps onto the small side, and the pivot swaps in just after it, placed for good. The parts still to sort wait in a list, each kept as its first and last place. Plain quick sort always takes the last number, so a row in order is its dearest: 28 comparisons on 10, 20, up to 80. With random picks, that row cost 15 here, as section 3 draws. The picks come from the site's own generator, the same picks each time you watch the same row.

2612401833pivot: picked at random3312401826pivot moved to the end3312401826not smaller: stays1233401826smaller: swapped left1233401826not smaller: stays1218403326smaller: swapped left1218263340pivot placed
One split of 26, 12, 40, 18, 33. The 26 is picked, moved to the end, and the split runs round it. The line under the row marks the small side, the rest is the big side, and the yellow triangle marks the number just compared.
level04273118562312491718122356493142271218234249315637121823423149564712182331424956
Every split of 42, 7, 31, 18, 56, 23, 12, 49 with its picks. Each row is the row above after its splits. A solid square is the number a part places, and a blue circle was placed in an earlier row.
A short shuffle: 6 moments of its 43 steps, the steps between them left for the watch page
  1. step 2 of 43

    427311856231249

    Sort the part from place 1 to place 8. Pick one of its places at random: place 6, so its number, 23, is the pivot.

    what it remembers to know where it is
    pivot
    23
    place picked
    6
    part starts at place
    1
    part ends at place
    8
    looking at place
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 3 of 43

    427311856491223

    Swap the pivot 23 to the end of the part, out of the way, and 49 goes where 23 was.

    what it remembers to know where it is
    pivot
    23
    place picked
    6
    part starts at place
    1
    part ends at place
    8
    looking at place
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  3. step 6 of 43

    742311856491223

    Swap 7 onto the small side, and 42 goes where 7 was.

    what it remembers to know where it is
    pivot
    23
    place picked
    not yet
    part starts at place
    1
    part ends at place
    8
    looking at place
    2

    Where it says not yet, nothing is held there at that moment.

    watch from here

  4. step 14 of 43

    718122356493142

    Swap the pivot 23 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.

    what it remembers to know where it is
    pivot
    23
    place picked
    not yet
    part starts at place
    1
    part ends at place
    8
    looking at place
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  5. step 16 of 43

    718122356493142

    Sort the part from place 1 to place 3. Pick one of its places at random: place 3, so its number, 12, is the pivot.

    what it remembers to know where it is
    pivot
    12
    place picked
    3
    part starts at place
    1
    part ends at place
    3
    looking at place
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  6. step 43 of 43

    712182331424956

    In order, after 15 comparisons and 9 swaps.

    what it remembers to know where it is
    pivot
    not yet
    place picked
    not yet
    part starts at place
    not yet
    part ends at place
    not yet
    looking at place
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. sort the whole row as one partPython line 14
  2. a part of one number is in placePython lines 17 and 18
  3. pick a place in the part at random, and its number is the pivotPython line 20
  4. swap the pivot to the end of the part, out of the wayPython lines 21, 22 and 23
  5. look at each other number in the part, from the leftPython line 25
  6. if it is smaller than the pivot, swap it onto the small sidePython lines 24, 26, 27 and 28
  7. swap the pivot in just after the small side, where it staysPython lines 30 and 31
  8. sort the part on its left, then the part on its rightPython lines 15, 16, 32 and 33
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

import random


def randomised_quick_sort(numbers, pick=random.randint):
    """Put a list of numbers in order, smallest first, in the list itself.

    Each part of the list gets a pivot picked at random: pick(low, high)
    gives a place from low to high, each as likely. The pivot is swapped to
    the part's end, out of the way, and the part is split round it as quick
    sort splits it: every smaller number is swapped onto a small side at the
    left, and the pivot is swapped in just after it, where it stays. Then the
    part on each side is sorted the same way, the left one first.
    """
    parts = [(0, len(numbers) - 1)]  # sort the whole list as one part
    while parts:
        low, high = parts.pop()
        if low >= high:  # a part of one number, or none, is in place
            continue

        chosen = pick(low, high)  # a place in the part, at random
        # the pivot goes to the end of the part, out of the way
        numbers[chosen], numbers[high] = numbers[high], numbers[chosen]
        pivot = numbers[high]
        small = low  # where the small side ends
        for place in range(low, high):  # each other number, from the left
            if numbers[place] < pivot:  # smaller: onto the small side
                numbers[small], numbers[place] = numbers[place], numbers[small]
                small += 1

        # the pivot goes just after the small side, and stays there
        numbers[small], numbers[high] = numbers[high], numbers[small]
        parts.append((small + 1, high))  # the part on its right waits,
        parts.append((low, small - 1))  # the part on its left goes first
    return numbers

how it scales

How the comparisons grow, from ten numbers to ten million.

Each step across or up is ten times the one before, a log-log plot. The line climbs only a little more than one step up for each step across. It is the average over the picks, the same for a row in order as for a shuffle. Each point is 20 shuffles, each sorted once, which averages the same as one row sorted again and again.

comparisons, ten times more at each mark up

a secondslope 1.1102104106108101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107

nn, how many numbers are in the row, ten times more at each mark to the right

  • every row of different numbers, averaged over the pickssolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, about 12 times the work
what a shuffled row costs on average, at a billion comparisons a second
nncomparisonstime
1,00010,986about 11 microseconds
100,0002,018,053about 2 milliseconds
10,000,000293,906,261about 294 milliseconds

The comparisons are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

import random


def randomised_quick_sort(numbers, pick=random.randint):
    """Put a list of numbers in order, smallest first, in the list itself.

    Each part of the list gets a pivot picked at random: pick(low, high)
    gives a place from low to high, each as likely. The pivot is swapped to
    the part's end, out of the way, and the part is split round it as quick
    sort splits it: every smaller number is swapped onto a small side at the
    left, and the pivot is swapped in just after it, where it stays. Then the
    part on each side is sorted the same way, the left one first.
    """
    parts = [(0, len(numbers) - 1)]  # sort the whole list as one part
    while parts:
        low, high = parts.pop()
        if low >= high:  # a part of one number, or none, is in place
            continue

        chosen = pick(low, high)  # a place in the part, at random
        # the pivot goes to the end of the part, out of the way
        numbers[chosen], numbers[high] = numbers[high], numbers[chosen]
        pivot = numbers[high]
        small = low  # where the small side ends
        for place in range(low, high):  # each other number, from the left
            if numbers[place] < pivot:  # smaller: onto the small side
                numbers[small], numbers[place] = numbers[place], numbers[small]
                small += 1

        # the pivot goes just after the small side, and stays there
        numbers[small], numbers[high] = numbers[high], numbers[small]
        parts.append((small + 1, high))  # the part on its right waits,
        parts.append((low, small - 1))  # the part on its left goes first
    return numbers


# Count randomised quick sort's comparisons yourself, as the plot on this page
# does. Run this file with Python 3.12 or later. For each size n it prints the
# average comparisons over 20 runs on a row in order and on 20 shuffles. Your
# picks are random, so your numbers will differ a little from the page's; the
# counts do not depend on the computer, only the time taken does.


class Counted:
    """A number that counts every comparison made with it."""

    comparisons = 0

    def __init__(self, value):
        self.value = value

    def __lt__(self, other):
        Counted.comparisons += 1
        return self.value < other.value


def count(row, pick=random.randint):
    """How many comparisons randomised quick sort makes on this row."""
    Counted.comparisons = 0
    randomised_quick_sort([Counted(x) for x in row], pick)
    return Counted.comparisons


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>7} {'in order':>10} {'shuffled':>10}")
    for n in [10, 100, 1000, 10000]:
        in_order = sum(count(list(range(1, n + 1))) for _ in range(20)) / 20
        shuffles = []
        for _ in range(20):
            row = list(range(1, n + 1))
            random.shuffle(row)
            shuffles.append(count(row))
        print(f"{n:>7} {in_order:>10.1f} {sum(shuffles) / 20:>10.1f}")

extra memory, the places the sort holds beyond the row itself, ten times more at each mark up

102101102103104105106107101102101102103104105106107101102101102103104105106107

nn, how many numbers are in the row, ten times more at each mark to the right

  • every row of different numbers, averaged over the pickspoints only, each measured by a real run, since no single formula for the extra memory of this row is worked out here

best, worst and average

The picks decide the cost, not the order of the row, so the grid has one column, the average over the picks, on any row of different numbers. For 1, 2, 3 it is 8 over 3, as section 4 counts. The luckiest picks cost what quick sort's cheapest row costs, and the unluckiest what its dearest costs: on 8 numbers, 13 and 28. The quick sort page works both out. The second picture shows the 28: its row is dear because of its picks, not its order.

A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
averageevery row of different numbers, averaged over the picks
comparisons2(n+1)H(n)−4n2(n + 1)H(n) - 4n
how the comparisons grow in each case
tight, Θ\ThetaΘ(n log⁡2 n)\Theta(n \,\log_2\, n)
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n)
floor, Ω\OmegaΩ(n log⁡2 n)\Omega(n \,\log_2\, n)

extra memory: a list of the parts waiting to be sorted, each kept as its first and last place. On average far shorter than the row, about 66 places for a million numbers. Unlucky picks can make it grow with the row

Extra memory is the room it needs on top of the input itself, while it runs.

levelcomparisons01020304050607080711020304050607080521020304050607080331020304050607080015
A row in order, quick sort's dearest at 28 comparisons. With its picks here it costs 7 + 5 + 3 = 15.
levelcomparisons012424931723561871124249317231856621242183172349565374218312312495644712183123424956357121831234249562671218233142495617712182331424956028
Bad luck. Every pick is the biggest or smallest left, so each part is only one shorter. 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28 comparisons.

where the formula comes from

Each count above, worked out in small steps. Every step names the line it uses.

Why does any row of different numbers cost 2(n+1)H(n)−4n2(n + 1)H(n) - 4n comparisons, averaged over the picks?
  1. the move: name the numbers

    the line:
    any row of n different numbers,called 1 to n\begin{gathered} \text{any row of } n \text{ different numbers,} \\ \text{called } 1 \text{ to } n \end{gathered}

    why it is allowed: The average here is over the picks, on one row. The splits care only which number is smaller than which, so call the smallest 1, the next 2, and on up. So 26, 12, 40 become 2, 1, 3.

  2. the move: watch two numbers

    the line:
    until one of the numbersfrom i to j is picked,they all stay in one part\begin{gathered} \text{until one of the numbers} \\ \text{from } i \text{ to } j \text{ is picked,} \\ \text{they all stay in one part} \end{gathered}
    first pivot25so
    7left partleft partthey wait in one part
    3left partright partthey never meet
    2the pivotcompared with 2they meet
    5compared with 5the pivotthey meet
    Watching 2 and 5 in 1 to 8. A pivot outside 2 to 5 keeps them together, as in line 2; 3 or 4 parts them, line 3; 2 or 5 compares them, line 4.

    why it is allowed: Take two numbers, ii the smaller and jj the bigger. A pivot below ii or above jj sends every number from ii to jj the same way. The table watches 2 and 5 in 1 to 8.

  3. the move: a number between parts them

    the line:
    if the first of them pickedis between i and j,they never meet\begin{gathered} \text{if the first of them picked} \\ \text{is between } i \text{ and } j \text{,} \\ \text{they never meet} \end{gathered}

    why it is allowed: That pivot sends ii left and jj right, into different parts. Every comparison is with a pivot, and neither of them was one before, or is one now, so they never meet.

  4. the move: an end meets the other

    the line:
    if it is i or j,they meet, just once\begin{gathered} \text{if it is } i \text{ or } j, \\ \text{they meet, just once} \end{gathered}

    why it is allowed: Every comparison is with a pivot, and neither was one before, so they have not met yet. By line 2 the other is still in its part, so the split compares them. The pivot is then placed, outside both parts, so they never meet again.

  5. the move: see each picked first equally often

    the line:
    they meet with a chanceof 2 in j−i+1\begin{gathered} \text{they meet with a chance} \\ \text{of 2 in } j - i + 1 \end{gathered}
    first pickthen1, 3 meetcomparisons
    1split 2, 3yes3
    2two lone numbersno2
    3split 1, 2yes3
    average2 in 38 over 3
    The row 1, 2, 3 and each first pick, each as likely. Whatever comes after costs the same either way.

    why it is allowed: Every pick is as likely to land on one place of its part as on any other. While the numbers from ii to jj share a part, a pick landing on one of them is as likely to land on any of the others. So each of the j−i+1j - i + 1 numbers is as likely to be picked first. By lines 3 and 4, the pair meets when it is ii or jj. In the table, 1 and 3 meet with a chance of 2 in 3.

  6. the move: add the pairs' chances

    the line:
    the average comparisons arethe pairs’ chances added up\begin{gathered} \text{the average comparisons are} \\ \text{the pairs' chances added up} \end{gathered}
    pairapartnumbers from one to the otherchance of meeting
    1, 2122 in 2
    2, 3122 in 2
    1, 3232 in 3
    in all8 over 3
    The row 1, 2, 3 pair by pair, each chance from line 5. The chances add up to the average, 8 over 3.

    why it is allowed: A pair adds 1 comparison to a run when it meets, by line 4, and 0 when it does not. So on average it adds its chance of meeting. Averages add, as the expected-cost page shows in its pairs question, line 2. For 1, 2, 3, the table adds 1, 1 and 2 in 3: 8 over 3, the average at line 5.

  7. the move: group the pairs by how far apart

    the line:
    A=(n−1)22+(n−2)23+…+(n−k)2k+1+⋯+1⋅2n\begin{gathered} A = (n - 1)\frac{2}{2} + (n - 2)\frac{2}{3} + \dots \\ + (n - k)\frac{2}{k + 1} + \dots + 1 \cdot \frac{2}{n} \end{gathered}

    why it is allowed: AA is the comparisons averaged over the picks. Two numbers stand kk apart when the bigger is the smaller plus kk, with kk from 1 to n−1n - 1, so each pair is in one group. Each of 1, 2, and on up to n−kn - k has a partner kk above it, so n−kn - k pairs stand kk apart. For 4 numbers, 1 apart are 1 and 2, 2 and 3, 3 and 4; 2 apart, 1 and 3, 2 and 4; 3 apart, 1 and 4. From ii to jj there are k+1k + 1 numbers, so by line 5 each meets with a chance of 2 in k+1k + 1. Line 6 adds them. For 4 numbers: 3 pairs at 2 in 2, 2 at 2 in 3, 1 at 2 in 4. That is 3, plus 4 thirds, plus a half, 29 over 6.

  8. the move: write each term with its bottom

    the line:
    A=(n+1−2)22+(n+1−3)23+⋯+(n+1−n)2n\begin{gathered} A = (n + 1 - 2)\frac{2}{2} + (n + 1 - 3)\frac{2}{3} \\ + \dots + (n + 1 - n)\frac{2}{n} \end{gathered}

    why it is allowed: Each term's bottom is k+1k + 1, from 2 to nn. Its count of pairs, n−kn - k, is n+1n + 1 take away that bottom; for the first term, n−1n - 1 is n+1−2n + 1 - 2.

  9. the move: multiply out each term

    the line:
    A=(2(n+1)2−2)+(2(n+1)3−2)+…+(2(n+1)n−2)\begin{gathered} A = \Bigl(\frac{2(n + 1)}{2} - 2\Bigr) \\ + \Bigl(\frac{2(n + 1)}{3} - 2\Bigr) + \dots \\ + \Bigl(\frac{2(n + 1)}{n} - 2\Bigr) \end{gathered}

    why it is allowed: The second term, (n+1−3)23(n + 1 - 3)\frac{2}{3}, is 2(n+1)3−2\frac{2(n + 1)}{3} - 2, since 3 times 2 over 3 is 2. Every term takes away 2 the same way.

  10. the move: take out the common part, add up the 2s

    the line:
    A=2(n+1)(12+13+⋯+1n)−2(n−1)\begin{gathered} A = 2(n + 1)\Bigl(\frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n}\Bigr) \\ - 2(n - 1) \end{gathered}

    why it is allowed: The n−1n - 1 terms of line 9 each take away 2, and each hold 2(n+1)2(n + 1) over their bottom.

  11. the move: name the harmonic sum

    the line:
    A=2(n+1)(H(n)−1)−2(n−1)A = 2(n + 1)\bigl(H(n) - 1\bigr) - 2(n - 1)
    where does this come from?
    question 4 of the page expected costHow does 1+12+13+⋯+1n1 + \frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n} grow?
    1. the move: name the sum

      the line:
      H=∑k=1n1kH = \sum_{k=1}^{n} \frac{1}{k}

      why it is allowed: Let HH be the harmonic sum to 1 over nn, for nn from 2.

    2. the move: group in blocks

      the line:
      blocks, each starting at1 over a power of 2\begin{gathered} \text{blocks, each starting at} \\ \text{1 over a power of 2} \end{gathered}
      blocktermsadds to01≤ 112≤ 124≤ 135≤ 1
      The sum to 1 over 12, about 3.10, each term a column 1 over k tall. Behind each place of a block stands its first term, dashed, so 4 dashed columns of 1 over 4 make 1. The last block is cut short.

      why it is allowed: Number blocks by jj from 0. Block jj starts at 1 over 2 to the power jj: 1, 1 over 2, 1 over 4, 1 over 8. It stops just before the next start, so it has 2 to the power jj terms: 1 over 4 to 1 over 7 are 4. The last block may be cut short at 1 over nn.

    3. the move: each block at most 1

      the line:
      H≤the number of blocksH \le \text{the number of blocks}

      why it is allowed: Each term of block jj is at most its first, 1 over 2 to the power jj, as a bigger number underneath makes a smaller fraction. So its 2 to the power jj terms, or fewer, add to at most 1. HH is at most 1 per block: 4 for 12.

    4. the move: count the blocks

      the line:
      H≤⌊log⁡2 n⌋+1H \le \lfloor \log_2\, n \rfloor + 1
      where does this come from?
      question 2 of the page halving and logarithmsHalve nn, rounding down each time. How many halvings reach 1?
      1. the move: name the log rounded down

        the line:
        K=⌊log⁡2 n⌋K = \lfloor \log_2\, n \rfloor
        numberlog× 2+ 14283164113.46352.322211100
        Rounding down, 11 halves to 5, 2 and 1. In blue, each log rounded down: 3, 2, 1, 0, one less at each halving.

        why it is allowed: Here nn is the number halved, from 2 up; for 11, KK is 3.

      2. the move: rounding down never adds

        the line:
        ⌊log⁡2 n⌋≤log⁡2 n\lfloor \log_2\, n \rfloor \le \log_2\, n

        why it is allowed: For 11, 3 is at most 3.46.

      3. the move: rounding down takes off less than 1

        the line:
         log⁡2 n<⌊log⁡2 n⌋+1\begin{gathered} \,\log_2\, n \\ < \lfloor \log_2\, n \rfloor + 1 \end{gathered}

        why it is allowed: For 11, 4 is above 3.46.

      4. the move: raise 2 to each side of line 2

        the line:
        2⌊log⁡2 n⌋≤2log⁡2 n2^{\lfloor \log_2\, n \rfloor} \le 2^{\log_2\, n}

        why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.

      5. the move: 2 to the log of n is n

        the line:
        2⌊log⁡2 n⌋≤n2^{\lfloor \log_2\, n \rfloor} \le n

        why it is allowed: By what a log is. For 11, 8 is at most 11.

      6. the move: raise 2 to each side of line 3

        the line:
        2log⁡2 n<2⌊log⁡2 n⌋+12^{\log_2\, n} < 2^{\lfloor \log_2\, n \rfloor + 1}

        why it is allowed: As in line 4. For 11, about 11 is below 16.

      7. the move: 2 to the log of n is n

        the line:
        n<2⌊log⁡2 n⌋+1n < 2^{\lfloor \log_2\, n \rfloor + 1}

        why it is allowed: As in line 5. For 11, 11 is below 16.

      8. the move: halve both sides of line 5

        the line:
        2⌊log⁡2 n⌋/2≤n/22^{\lfloor \log_2\, n \rfloor} / 2 \le n / 2

        why it is allowed: For 11, 4 is at most 5.5, which is not whole.

      9. the move: write the half as a power

        the line:
        2⌊log⁡2 n⌋−1≤n/22^{\lfloor \log_2\, n \rfloor - 1} \le n / 2

        why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.

      10. the move: round the half down

        the line:
        2⌊log⁡2 n⌋−1≤⌊n/2⌋2^{\lfloor \log_2\, n \rfloor - 1} \le \lfloor n / 2 \rfloor

        why it is allowed: ⌊n/2⌋\lfloor n / 2 \rfloor is the half rounded down, 5 for 11. A whole number at most 5.5 is at most 5. The left side, 4 for 11, is whole, as KK is at least 1 for nn from 2 up.

      11. the move: halve both sides of line 7

        the line:
        n/2<2⌊log⁡2 n⌋+1/2n / 2 < 2^{\lfloor \log_2\, n \rfloor + 1} / 2

        why it is allowed: For 11, 5.5 is below 8.

      12. the move: write the half as a power

        the line:
        n/2<2⌊log⁡2 n⌋n / 2 < 2^{\lfloor \log_2\, n \rfloor}

        why it is allowed: As in line 9. Half of 16 is 8.

      13. the move: round the half down

        the line:
        ⌊n/2⌋<2⌊log⁡2 n⌋\lfloor n / 2 \rfloor < 2^{\lfloor \log_2\, n \rfloor}

        why it is allowed: Rounding down never adds. For 11, 5 is below 8.

      14. the move: take the log of line 10

        the line:
         log⁡2 2⌊log⁡2 n⌋−1≤log⁡2 ⌊n/2⌋\begin{gathered} \,\log_2\, 2^{\lfloor \log_2\, n \rfloor - 1} \\ \le \log_2\, \lfloor n / 2 \rfloor \end{gathered}

        why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.

      15. the move: the log of a power of 2 is the power

        the line:
        ⌊log⁡2 n⌋−1≤log⁡2 ⌊n/2⌋\begin{gathered} \lfloor \log_2\, n \rfloor - 1 \\ \le \log_2\, \lfloor n / 2 \rfloor \end{gathered}

        why it is allowed: For 11, the log of 4 is 2, at most about 2.32.

      16. the move: take the log of line 13

        the line:
         log⁡2 ⌊n/2⌋<log⁡2 2⌊log⁡2 n⌋\begin{gathered} \,\log_2\, \lfloor n / 2 \rfloor \\ < \log_2\, 2^{\lfloor \log_2\, n \rfloor} \end{gathered}

        why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.

      17. the move: the log of a power of 2 is the power

        the line:
         log⁡2 ⌊n/2⌋<⌊log⁡2 n⌋\begin{gathered} \,\log_2\, \lfloor n / 2 \rfloor \\ < \lfloor \log_2\, n \rfloor \end{gathered}

        why it is allowed: For 11, about 2.32 is below 3.

      18. the move: round the log down

        the line:
        ⌊log⁡2 ⌊n/2⌋⌋=⌊log⁡2 n⌋−1\begin{gathered} \lfloor \log_2\, \lfloor n / 2 \rfloor \rfloor \\ = \lfloor \log_2\, n \rfloor - 1 \end{gathered}
        the numberat leastbelowits log rounded down
        118163
        5482
        2241
        1120
        Each halving takes 1 off the log rounded down.

        why it is allowed: By lines 15 and 17, the log of the half is at least one less than KK and below KK, so it rounds down to one less. For 11, about 2.32 rounds down to 2.

      19. the move: use line 18 again and again

        the line:
        after K halvings,rounding down,the log roundeddown is 0\begin{gathered} \text{after } K \text{ halvings,} \\ \text{rounding down,} \\ \text{the log rounded} \\ \text{down is 0} \end{gathered}

        why it is allowed: While the log rounded down is 1 or more, the number is at least 2 to the power 1, which is 2. So line 18 takes 1 off each halving, down to 0 after KK. For 11, 3, 2, 1, 0.

      20. the move: a log rounded down to 0 belongs to 1

        the line:
        K halvings,rounding down,bring n to 1\begin{gathered} K \text{ halvings,} \\ \text{rounding down,} \\ \text{bring } n \text{ to 1} \end{gathered}

        why it is allowed: Such a log is at least 0 and below 1, so its number is at least 1 and below 2. It is 1.

      the whole page: halving and logarithms

      why it is allowed: ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor is read the log of nn rounded down. By lines 5 and 7 of the page halving and logarithms, 2 to that power is at most nn, and the next power of 2 is above nn. So ⌊log⁡2 n⌋+1\lfloor \log_2\, n \rfloor + 1 blocks start at 1 over 2 to the powers 0 to ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor. For 12, 3.58 rounds down to 3: the 4 blocks of line 2.

    5. the move: drop the rounding

      the line:
      H≤log⁡2 n+1H \le \log_2\, n + 1

      why it is allowed: Rounding down never adds, so putting log⁡2 n\log_2\, n for ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor can never lower the right side. For 12, 4 becomes about 4.58.

    6. the move: a fact about n

      the line:
      1≤log⁡2 n1 \le \log_2\, n

      why it is allowed: nn is at least 2, the log of 2 is 1, and a bigger number has a bigger log.

    7. the move: put the log in place of the 1

      the line:
      H≤log⁡2 n+log⁡2 nH \le \log_2\, n + \log_2\, n

      why it is allowed: By line 6 this makes the right side of line 5 no smaller. For 12, 4.58 becomes about 7.17.

    8. the move: add the logs

      the line:
      H≤2 log⁡2 nH \le 2 \,\log_2\, n

      why it is allowed: Two lots of log⁡2 n\log_2\, n.

    9. the move: a ceiling

      the line:
      H∈O(log⁡2 n)H \in O(\log_2\, n)

      why it is allowed: By line 8, HH is at most 2 times log⁡2 n\log_2\, n for every nn from 2. H∈O(log⁡2 n)H \in O(\log_2\, n), read HH is in big O of log⁡2 n\log_2\, n, says a fixed multiple of log⁡2 n\log_2\, n is a ceiling of HH: here 2.

    10. the move: blocks after the first term

      the line:
      after the first term,blocks, each ending at1 over a power of 2\begin{gathered} \text{after the first term,} \\ \text{blocks, each ending at} \\ \text{1 over a power of 2} \end{gathered}
      blocktermsadds tofirst11≥ ½22≥ ½34≥ ½left over
      The sum to 1 over 12. Inside each term of a block stands its last term, dashed, so 2 dashed columns of 1 over 4 make one half. 1 over 9 to 1 over 12 are left over.

      why it is allowed: For a floor, group the terms after the first in blocks ending at 1 over 2, 1 over 4, 1 over 8 and on. Each term is then at least its block's last. Whole blocks end at 1 over the powers of 2 from 2 to nn.

    11. the move: drop the leftovers

      the line:
      H is at least 1 plusthe whole blocksadded up\begin{gathered} H \text{ is at least 1 plus} \\ \text{the whole blocks} \\ \text{added up} \end{gathered}

      why it is allowed: Leftover terms are above zero, so leaving them out makes the total no bigger.

    12. the move: whole blocks at least one half

      the line:
      H≥1+12×the numberof whole blocks\begin{gathered} H \ge 1 + \frac{1}{2} \times \text{the number} \\ \text{of whole blocks} \end{gathered}

      why it is allowed: Number the whole blocks by ii from 1. Block ii runs from just after 1 over half of 2 to the power ii to 1 over 2 to the power ii. That is half that many terms, each at least its last, so at least one half. For 12, 1 over 3 + 1 over 4 is at least 2 times 1 over 4. With line 11, HH is at least 1 plus one half per whole block: 2.5.

    13. the move: count the whole blocks

      the line:
      H≥1+⌊log⁡2 n⌋2H \ge 1 + \frac{\lfloor \log_2\, n \rfloor}{2}
      where does this come from?
      question 2 of the page halving and logarithmsHalve nn, rounding down each time. How many halvings reach 1?
      1. the move: name the log rounded down

        the line:
        K=⌊log⁡2 n⌋K = \lfloor \log_2\, n \rfloor
        numberlog× 2+ 14283164113.46352.322211100
        Rounding down, 11 halves to 5, 2 and 1. In blue, each log rounded down: 3, 2, 1, 0, one less at each halving.

        why it is allowed: Here nn is the number halved, from 2 up; for 11, KK is 3.

      2. the move: rounding down never adds

        the line:
        ⌊log⁡2 n⌋≤log⁡2 n\lfloor \log_2\, n \rfloor \le \log_2\, n

        why it is allowed: For 11, 3 is at most 3.46.

      3. the move: rounding down takes off less than 1

        the line:
         log⁡2 n<⌊log⁡2 n⌋+1\begin{gathered} \,\log_2\, n \\ < \lfloor \log_2\, n \rfloor + 1 \end{gathered}

        why it is allowed: For 11, 4 is above 3.46.

      4. the move: raise 2 to each side of line 2

        the line:
        2⌊log⁡2 n⌋≤2log⁡2 n2^{\lfloor \log_2\, n \rfloor} \le 2^{\log_2\, n}

        why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.

      5. the move: 2 to the log of n is n

        the line:
        2⌊log⁡2 n⌋≤n2^{\lfloor \log_2\, n \rfloor} \le n

        why it is allowed: By what a log is. For 11, 8 is at most 11.

      6. the move: raise 2 to each side of line 3

        the line:
        2log⁡2 n<2⌊log⁡2 n⌋+12^{\log_2\, n} < 2^{\lfloor \log_2\, n \rfloor + 1}

        why it is allowed: As in line 4. For 11, about 11 is below 16.

      7. the move: 2 to the log of n is n

        the line:
        n<2⌊log⁡2 n⌋+1n < 2^{\lfloor \log_2\, n \rfloor + 1}

        why it is allowed: As in line 5. For 11, 11 is below 16.

      8. the move: halve both sides of line 5

        the line:
        2⌊log⁡2 n⌋/2≤n/22^{\lfloor \log_2\, n \rfloor} / 2 \le n / 2

        why it is allowed: For 11, 4 is at most 5.5, which is not whole.

      9. the move: write the half as a power

        the line:
        2⌊log⁡2 n⌋−1≤n/22^{\lfloor \log_2\, n \rfloor - 1} \le n / 2

        why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.

      10. the move: round the half down

        the line:
        2⌊log⁡2 n⌋−1≤⌊n/2⌋2^{\lfloor \log_2\, n \rfloor - 1} \le \lfloor n / 2 \rfloor

        why it is allowed: ⌊n/2⌋\lfloor n / 2 \rfloor is the half rounded down, 5 for 11. A whole number at most 5.5 is at most 5. The left side, 4 for 11, is whole, as KK is at least 1 for nn from 2 up.

      11. the move: halve both sides of line 7

        the line:
        n/2<2⌊log⁡2 n⌋+1/2n / 2 < 2^{\lfloor \log_2\, n \rfloor + 1} / 2

        why it is allowed: For 11, 5.5 is below 8.

      12. the move: write the half as a power

        the line:
        n/2<2⌊log⁡2 n⌋n / 2 < 2^{\lfloor \log_2\, n \rfloor}

        why it is allowed: As in line 9. Half of 16 is 8.

      13. the move: round the half down

        the line:
        ⌊n/2⌋<2⌊log⁡2 n⌋\lfloor n / 2 \rfloor < 2^{\lfloor \log_2\, n \rfloor}

        why it is allowed: Rounding down never adds. For 11, 5 is below 8.

      14. the move: take the log of line 10

        the line:
         log⁡2 2⌊log⁡2 n⌋−1≤log⁡2 ⌊n/2⌋\begin{gathered} \,\log_2\, 2^{\lfloor \log_2\, n \rfloor - 1} \\ \le \log_2\, \lfloor n / 2 \rfloor \end{gathered}

        why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.

      15. the move: the log of a power of 2 is the power

        the line:
        ⌊log⁡2 n⌋−1≤log⁡2 ⌊n/2⌋\begin{gathered} \lfloor \log_2\, n \rfloor - 1 \\ \le \log_2\, \lfloor n / 2 \rfloor \end{gathered}

        why it is allowed: For 11, the log of 4 is 2, at most about 2.32.

      16. the move: take the log of line 13

        the line:
         log⁡2 ⌊n/2⌋<log⁡2 2⌊log⁡2 n⌋\begin{gathered} \,\log_2\, \lfloor n / 2 \rfloor \\ < \log_2\, 2^{\lfloor \log_2\, n \rfloor} \end{gathered}

        why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.

      17. the move: the log of a power of 2 is the power

        the line:
         log⁡2 ⌊n/2⌋<⌊log⁡2 n⌋\begin{gathered} \,\log_2\, \lfloor n / 2 \rfloor \\ < \lfloor \log_2\, n \rfloor \end{gathered}

        why it is allowed: For 11, about 2.32 is below 3.

      18. the move: round the log down

        the line:
        ⌊log⁡2 ⌊n/2⌋⌋=⌊log⁡2 n⌋−1\begin{gathered} \lfloor \log_2\, \lfloor n / 2 \rfloor \rfloor \\ = \lfloor \log_2\, n \rfloor - 1 \end{gathered}
        the numberat leastbelowits log rounded down
        118163
        5482
        2241
        1120
        Each halving takes 1 off the log rounded down.

        why it is allowed: By lines 15 and 17, the log of the half is at least one less than KK and below KK, so it rounds down to one less. For 11, about 2.32 rounds down to 2.

      19. the move: use line 18 again and again

        the line:
        after K halvings,rounding down,the log roundeddown is 0\begin{gathered} \text{after } K \text{ halvings,} \\ \text{rounding down,} \\ \text{the log rounded} \\ \text{down is 0} \end{gathered}

        why it is allowed: While the log rounded down is 1 or more, the number is at least 2 to the power 1, which is 2. So line 18 takes 1 off each halving, down to 0 after KK. For 11, 3, 2, 1, 0.

      20. the move: a log rounded down to 0 belongs to 1

        the line:
        K halvings,rounding down,bring n to 1\begin{gathered} K \text{ halvings,} \\ \text{rounding down,} \\ \text{bring } n \text{ to 1} \end{gathered}

        why it is allowed: Such a log is at least 0 and below 1, so its number is at least 1 and below 2. It is 1.

      the whole page: halving and logarithms

      why it is allowed: As in line 4, whole blocks end at 1 over 2 to the powers 1 to ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor, that many blocks. For 12, 3.

    14. the move: rounding takes off less than 1

      the line:
      H≥1+log⁡2 n−12H \ge 1 + \frac{\log_2\, n - 1}{2}

      why it is allowed: Rounding down takes off less than 1, so putting log⁡2 n\log_2\, n less 1 for ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor can only lower the right side. For 12, 2.5 becomes about 2.29.

    15. the move: halve each part

      the line:
      H≥1+log⁡2 n2−12H \ge 1 + \frac{\log_2\, n}{2} - \frac{1}{2}

      why it is allowed: Half of (log⁡2 n\log_2\, n less 1) is half of log⁡2 n\log_2\, n, less one half.

    16. the move: change the order

      the line:
      H≥1−12+log⁡2 n2H \ge 1 - \frac{1}{2} + \frac{\log_2\, n}{2}

      why it is allowed: Adding and taking away go in any order.

    17. the move: 1 less one half

      the line:
      H≥12+log⁡2 n2H \ge \frac{1}{2} + \frac{\log_2\, n}{2}

      why it is allowed: 1 less one half is one half.

    18. the move: drop the one half

      the line:
      H≥log⁡2 n2H \ge \frac{\log_2\, n}{2}

      why it is allowed: Taking away one half makes the right side smaller. For 12, about 1.79.

    19. the move: a floor

      the line:
      H∈Ω(log⁡2 n)H \in \Omega(\log_2\, n)
      the sumterms024681005101520the sumterms024681005101520
      • the ceiling, 2 log⁡2 n2 \,\log_2\, n
      • the harmonic sum
      • the floor, log⁡2 n2\frac{\log_2\, n}{2}
      From 2 terms on, the harmonic sum lies between its ceiling and floor. At 16: 8, about 3.38, and 2.

      why it is allowed: By line 18, HH is at least one half times log⁡2 n\log_2\, n for every nn from 2. H∈Ω(log⁡2 n)H \in \Omega(\log_2\, n), read HH is in big omega of log⁡2 n\log_2\, n, says a fixed multiple of log⁡2 n\log_2\, n, above zero, is a floor of HH.

    20. the move: ceiling and floor together

      the line:
      H∈Θ(log⁡2 n)H \in \Theta(\log_2\, n)

      why it is allowed: H∈Θ(log⁡2 n)H \in \Theta(\log_2\, n), read HH is in big theta of log⁡2 n\log_2\, n, says both: by lines 9 and 19, for every nn from 2, HH lies between one half and 2 times log⁡2 n\log_2\, n. It grows like log⁡2 n\log_2\, n.

    the whole page: expected cost

    why it is allowed: The bracket of line 10 is H(n)H(n) without its first 1. The fold shows how H(n)H(n) grows.

  12. the move: open the first bracket

    the line:
    A=2(n+1)H(n)−2(n+1)−2(n−1)A = 2(n + 1)H(n) - 2(n + 1) - 2(n - 1)

    why it is allowed: Taking 1 away inside the bracket takes away 2(n+1)2(n + 1).

  13. the move: gather

    the line:
    A=2(n+1)H(n)−4nA = 2(n + 1)H(n) - 4n

    why it is allowed: 2(n+1)2(n + 1) and 2(n−1)2(n - 1) add up to 4n4n, the 2 and the take-away 2 cancelling. For 3 numbers, H(3)H(3) is 1, plus a half, plus a third, which is 11 sixths. So 2 times 4 times 11 sixths, less 12, is 8 over 3, the tables' average. Nothing here hangs on the row's order, so every row of nn different numbers averages the same.

  14. the move: how big the harmonic sum gets

    the line:
    H(n)≤log⁡2 n+1 for n≥2H(n) \le \log_2\, n + 1 \text{ for } n \ge 2

    why it is allowed: The fold at line 11 shows this, in its line 5.

  15. the move: a ceiling

    the line:
    A≤2(n+1)(log⁡2 n+1)−4nA \le 2(n + 1)(\log_2\, n + 1) - 4n

    why it is allowed: Put line 14 into line 13. H(n)H(n) is multiplied by 2(n+1)2(n + 1), which is positive, so a bigger value in its place gives a ceiling. At 1 number AA is 0, so this holds there too.

  16. the move: open the bracket

    the line:
    A≤2(n+1) log⁡2 n+2(n+1)−4nA \le 2(n + 1)\,\log_2\, n + 2(n + 1) - 4n

    why it is allowed: Multiply 2(n+1)2(n + 1) by each of log⁡2 n\log_2\, n and 1.

  17. the move: gather

    the line:
    A≤2(n+1) log⁡2 n−2n+2A \le 2(n + 1)\,\log_2\, n - 2n + 2

    why it is allowed: 2(n+1)2(n + 1) less 4n4n leaves −2n+2- 2n + 2.

  18. the move: drop what is not positive

    the line:
    A≤2(n+1) log⁡2 nA \le 2(n + 1)\,\log_2\, n

    why it is allowed: From 1 number on, −2n+2- 2n + 2 is at most 0.

  19. the move: a simpler ceiling

    the line:
    A≤4n log⁡2 nA \le 4n \,\log_2\, n

    why it is allowed: n+1n + 1 is at most 2n2n, and log⁡2 n\log_2\, n is not negative.

  20. the move: read it as a bound

    the line:
    A∈O(n log⁡2 n)A \in O(n \,\log_2\, n)

    why it is allowed: By line 19, AA stays under 4 times n log⁡2 nn \,\log_2\, n.

  21. the move: how small the harmonic sum gets

    the line:
    H(n)≥12+log⁡2 n2 for n≥2H(n) \ge \frac{1}{2} + \frac{\log_2\, n}{2} \text{ for } n \ge 2

    why it is allowed: The fold at line 11 shows this, in its line 17.

  22. the move: a floor

    the line:
    A≥2(n+1)(12+log⁡2 n2)−4nA \ge 2(n + 1)\Bigl(\frac{1}{2} + \frac{\log_2\, n}{2}\Bigr) - 4n

    why it is allowed: Put line 21 into line 13. H(n)H(n) is multiplied by 2(n+1)2(n + 1), which is positive, so a smaller value in its place gives a floor. At 1 number AA is 0, and the right side is less.

  23. the move: take the 2 into the bracket

    the line:
    A≥(n+1)(1+log⁡2 n)−4nA \ge (n + 1)(1 + \log_2\, n) - 4n

    why it is allowed: 2 times a half is 1, and 2 times log⁡2 n2\frac{\log_2\, n}{2} is log⁡2 n\log_2\, n.

  24. the move: a smaller floor

    the line:
    A≥n(1+log⁡2 n)−4nA \ge n(1 + \log_2\, n) - 4n

    why it is allowed: n+1n + 1 is more than nn, and 1+log⁡2 n1 + \log_2\, n is positive.

  25. the move: open the bracket

    the line:
    A≥n log⁡2 n−3nA \ge n \,\log_2\, n - 3n

    why it is allowed: nn times 1 is nn, and nn less 4n4n is −3n- 3n.

  26. the move: what 16 numbers allow

    the line:
    3n≤34n log⁡2 n for n≥163n \le \frac{3}{4} n \,\log_2\, n \text{ for } n \ge 16

    why it is allowed: From 16 numbers on, log⁡2 n\log_2\, n is at least 4, so 34\frac{3}{4} of it is at least 3.

  27. the move: take away more

    the line:
    A≥n log⁡2 n−34n log⁡2 n for n≥16A \ge n \,\log_2\, n - \frac{3}{4} n \,\log_2\, n \text{ for } n \ge 16

    why it is allowed: Put line 26 into line 25. Taking away more leaves less, so the floor still holds.

  28. the move: tidy

    the line:
    A≥n log⁡2 n4 for n≥16A \ge \frac{n \,\log_2\, n}{4} \text{ for } n \ge 16

    why it is allowed: One whole n log⁡2 nn \,\log_2\, n, less three quarters of it, leaves a quarter of it.

  29. the move: read it as a bound

    the line:
    A∈Ω(n log⁡2 n)A \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 28, from 16 numbers on, AA stays above a quarter of n log⁡2 nn \,\log_2\, n.

  30. the move: ceiling and floor together

    the line:
    A∈Θ(n log⁡2 n)A \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 20 and 29 bound AA by the same growth, n log⁡2 nn \,\log_2\, n.

try it on small rows: over every order of 16 numbers, the average AA is about 50.94

Why does a row of equal numbers cost n(n−1)2\frac{n(n - 1)}{2} comparisons, whatever the picks?
  1. the move: no number is smaller

    the line:
    with every number equal,none is smaller than the pivot\begin{gathered} \text{with every number equal,} \\ \text{none is smaller than the pivot} \end{gathered}
    levelcomparisons0999994199999329999923999991499999010
    Five equal numbers. Each split places its pivot and leaves the rest in one part. 4 + 3 + 2 + 1 = 10 comparisons.

    why it is allowed: A split moves only numbers smaller than the pivot. Whatever place is picked, each split leaves all the others in one part, as the picture shows.

  2. the move: price one split

    the line:
    a split of m numbersmakes m−1 comparisons\begin{gathered} \text{a split of } m \text{ numbers} \\ \text{makes } m - 1 \text{ comparisons} \end{gathered}

    why it is allowed: Each number but the pivot is compared with the pivot, once.

  3. the move: add up the splits

    the line:
    E=(n−1)+(n−2)+⋯+1E = (n - 1) + (n - 2) + \dots + 1

    why it is allowed: EE is the comparisons on a row of nn equal numbers. By line 1 the parts hold nn, then n−1n - 1, and on down to 2 numbers. By line 2 each costs one less.

  4. the move: add the counting numbers

    the line:
    E=(n−1)((n−1)+1)2E = \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2}
    where does this come from?
    question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
    1. the move: draw the sum as a staircase

      the line:
      S=1+2+⋯+nS = 1 + 2 + \dots + n

      why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

    2. the move: take two staircases

      the line:
      2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

      why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

    3. the move: fit them into a rectangle

      the line:
      2S=n(n+1)2S = n(n + 1)
      Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

      why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

    4. the move: halve both sides

      the line:
      S=n(n+1)2S = \frac{n(n + 1)}{2}

      why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

    the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

    why it is allowed: The fold shows how to add the whole numbers from 1 up to any last number, with two staircases. Here the last number is n−1n - 1.

  5. the move: tidy

    the line:
    E=n(n−1)2E = \frac{n(n - 1)}{2}

    why it is allowed: (n−1)+1(n - 1) + 1 is nn. For 5 numbers, 5 times 4 over 2 is 10, as in the picture.

  6. the move: a ceiling

    the line:
    E≤n22E \le \frac{n^2}{2}

    why it is allowed: In line 5, n−1n - 1 is less than nn.

  7. the move: read it as a bound

    the line:
    E∈O(n2)E \in O(n^2)

    why it is allowed: By line 6, EE stays under half of n2n^2.

  8. the move: a floor

    the line:
    E≥n24 for n≥2E \ge \frac{n^2}{4} \text{ for } n \ge 2

    why it is allowed: In line 5, n−1n - 1 is at least half of nn once nn is 2 or more.

  9. the move: read it as a bound

    the line:
    E∈Ω(n2)E \in \Omega(n^2)

    why it is allowed: By line 8, from 2 numbers on, EE never drops below a quarter of n2n^2.

  10. the move: ceiling and floor together

    the line:
    E∈Θ(n2)E \in \Theta(n^2)

    why it is allowed: Lines 7 and 9 bound EE by the same growth, n2n^2.

try it with a small nn: at n=5n = 5, line 3 gives E=10E = 10, which you can work out by hand

On different numbers, how likely is it that every pick is the biggest or smallest left?
  1. the move: the unluckiest picks

    the line:
    if every pick is the biggestor smallest left, it costsn(n−1)2 comparisons\begin{gathered} \text{if every pick is the biggest} \\ \text{or smallest left, it costs} \\ \frac{n(n - 1)}{2} \text{ comparisons} \end{gathered}

    why it is allowed: Then each split leaves one part of all the rest, as with equal numbers. So lines 2 to 5 of the ladder before give the count, with this sentence in place of its line 1. The second picture of section 3 is such a run.

  2. the move: the chance at one split

    the line:
    a split of m numbers picksthe biggest or smallestin 2 of every m ways\begin{gathered} \text{a split of } m \text{ numbers picks} \\ \text{the biggest or smallest} \\ \text{in 2 of every } m \text{ ways} \end{gathered}

    why it is allowed: Each of the mm places is as likely, and two of them hold the biggest and the smallest.

  3. the move: every split unlucky

    the line:
    P=2n×2n−1×⋯×22P = \frac{2}{n} \times \frac{2}{n - 1} \times \dots \times \frac{2}{2}
    pickruns still unluckyunlucky this timeruns left
    first242 in 412
    second122 in 38
    third82 in 28
    24 runs on 4 different numbers, as the chances share them out, followed pick by pick. Half start unlucky, 2 in 3 of those stay unlucky, and all of those end unlucky. 8 of 24 is a third.

    why it is allowed: PP is the chance that every pick is the biggest or smallest left. Each pick is fair on its own part, whatever came before. The first pick is unlucky in 2 of every nn runs. Of those, the next is unlucky in 2 of every n−1n - 1, and on down to the part of 2. A share of a share multiplies, as the table follows 24 runs. For 4 numbers, 2 in 4, then 2 in 3 of those, then 2 in 2, is 8 in 24.

  4. the move: gather tops and bottoms

    the line:
    P=2n−1n!P = \frac{2^{n - 1}}{n!}

    why it is allowed: There are n−1n - 1 twos on top, and nn times n−1n - 1 and on down to 2 underneath, which is n!n!. For 4 numbers, 8 over 24, a third; for 8 numbers, 128 over 40,320, exactly 1 in 315.

try it with a small nn: at n=4n = 4, line 3 gives PP, about 0.33

count it yourself

Count every comparison on five equal numbers, then check the total against the formula for equal numbers.

9, 9, 9, 9, 9, every step written down
stepthe rowwhat happenscomparisonsswaps
19, 9, 9, 9, 9There are 5 numbers in a row. Sort the whole row as one part.9, 9, 9, 9, 900
29, 9, 9, 9, 9Sort the part from place 1 to place 5. Pick one of its places at random: place 3, so its number, 9, is the pivot.9, 9, 9, 9, 900
39, 9, 9, 9, 9Swap the pivot 9 to the end of the part, out of the way, and 9 goes where 9 was.9, 9, 9, 9, 901
49, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 911
59, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 921
69, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 931
79, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 941
89, 9, 9, 9, 9Swap the pivot 9 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.9, 9, 9, 9, 942
99, 9, 9, 9, 9Nothing lies to its left and 4 to its right: sort each side the same way, the left one first.9, 9, 9, 9, 942
109, 9, 9, 9, 9Sort the part from place 2 to place 5. Pick one of its places at random: place 4, so its number, 9, is the pivot.9, 9, 9, 9, 942
119, 9, 9, 9, 9Swap the pivot 9 to the end of the part, out of the way, and 9 goes where 9 was.9, 9, 9, 9, 943
129, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 953
139, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 963
149, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 973
159, 9, 9, 9, 9Swap the pivot 9 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.9, 9, 9, 9, 974
169, 9, 9, 9, 9Nothing lies to its left and 3 to its right: sort each side the same way, the left one first.9, 9, 9, 9, 974
179, 9, 9, 9, 9Sort the part from place 3 to place 5. Pick one of its places at random: place 4, so its number, 9, is the pivot.9, 9, 9, 9, 974
189, 9, 9, 9, 9Swap the pivot 9 to the end of the part, out of the way, and 9 goes where 9 was.9, 9, 9, 9, 975
199, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 985
209, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 995
219, 9, 9, 9, 9Swap the pivot 9 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.9, 9, 9, 9, 996
229, 9, 9, 9, 9Nothing lies to its left and 2 to its right: sort each side the same way, the left one first.9, 9, 9, 9, 996
239, 9, 9, 9, 9Sort the part from place 4 to place 5. Pick one of its places at random: place 4, so its number, 9, is the pivot.9, 9, 9, 9, 996
249, 9, 9, 9, 9Swap the pivot 9 to the end of the part, out of the way, and 9 goes where 9 was.9, 9, 9, 9, 997
259, 9, 9, 9, 99 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9107
269, 9, 9, 9, 9Swap the pivot 9 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.9, 9, 9, 9, 9108
279, 9, 9, 9, 9Nothing lies to its left and 1 to its right: sort each side the same way, the left one first.9, 9, 9, 9, 9108
289, 9, 9, 9, 99 is alone in its part, so it is in place for good.9, 9, 9, 9, 9108
299, 9, 9, 9, 9In order, after 10 comparisons and 8 swaps.9, 9, 9, 9, 9108

In all, 10 comparisons. The formula from section 4, n(n−1)2\frac{n(n - 1)}{2}, gives E=10E = 10 at n=5n = 5: the same.

where you meet it

A random pivot is one of the guards real sorts add to quick sort.

  • guarding quick sort's pivot

    Real sorts pick the pivot at random, or as the middle of a few numbers, so a row in order is not the dearest. The books' chapter 11 lists this first among quick sort's guards, the changes that keep it from a dear run. The sort built into the programming language C++, std::sort, takes the middle in size of three numbers of the part: of 40, 10 and 25, the 25.

    source: the books' volume one, chapter 11, its sidebar 'in the wild'; the GNU C++ library's stl_algo.h, as shipped with GCC 15, the part called __move_median_to_first

  • rows with many equal numbers

    A three-way split gathers the numbers equal to the pivot in a middle part, done at once. So 5, 3, 5, 8, 5 around a 5 becomes 3, then 5, 5, 5, then 8. That removes the dear row of equal numbers, as the books' chapter 11 lists among the guards.

    source: the books' volume one, chapter 11, its table of what a real sort adds

what is used instead

When the order of equal items must be kept, merge sort is used instead. When no bad luck at all is allowed, the C++ sort in GCC, an introsort, switches to heap sort after too many levels, as the quick sort page tells. Heap sort, another way to sort, has no dear row.

how it compares

Randomised quick sort beside the other ways to put a row in order, on one plot and in one table.

comparisons on a shuffled row, on the log-log scales of section 2, one line for each way whose page is written
102104106108101010121014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortshell sortquick sortmerge sortheap sortrandomised quick sort10110210310410510610710810910101011101210131014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortshell sortquick sortmerge sortheap sortrandomised quick sort
  • bubble sort
  • cocktail shaker sort
  • insertion sort
  • selection sort
  • shell sort
  • quick sort
  • randomised quick sort
  • merge sort
  • heap sort
put a row in order: each way side by side
waybestaverageworstextra memorykeeps equal items in orderworks in placereach for it when
bubble sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)a few spare places (the walk number, the pair's place, whether the walk swapped, room for a number while two swap), the same however long the rowyesyesyou are learning how sorting works; for real work, insertion sort, which on every order of up to 8 different numbers makes no more comparisons, counted order by order
cocktail shaker sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)a few spare places, the same however long the rowyesyesyou are learning how sorting works; for real work, insertion sort
insertion sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)room for a few numbers (the number being placed, where its slide has reached, which number is next), the same however long the rowyesyesthe row is short, a few dozen numbers, or nearly in order
selection sortΘ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)room for a few numbers (the place being filled, where the smallest so far stands, the number looked at, one held during a swap), the same however long the rownoyesmoving a number costs far more than comparing two, and the row is short
shell sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)not known; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)not worked out here; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)a few spare places (the gap, the number picked up, its place), the same however long the rownoyesyou want a few lines of code and no room beyond the row. On this site's shuffles of 200 to 10,000 numbers it averaged under a fifth of insertion sort's comparisons
quick sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2)a list of the parts still to sort, two memory places each. That is two places for each number on a row in order, and far fewer on a shuffle, about 51 for 100,000 numbers. So this plain version does not work in place, as its spare room grows with the rownonoyou want a fast sort on shuffled rows with no second row, and equal items need not keep their order; use a version with a random or middle pivot
randomised quick sortat most O(n log⁡2 n)O(n \,\log_2\, n), as every row of different numbers averages that over the picks; a row with equal numbers can cost a little lessΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2), a row of equal numbers, whatever the picks; no run costs more, since a pair meets at most oncea list of the parts waiting to be sorted, each kept as its first and last place. On average far shorter than the row, about 66 places for a million numbers. Unlucky picks can make it grow with the rownonoyou want quick sort without a dear row in order, and equal items need not keep their order
merge sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)a second row as long as the rowyesnoyou need comparisons growing no faster than n log⁡2 nn \,\log_2\, n on every row, equal items kept in order, or a file too big for memory sorted
heap sortΘ(n)\Theta(n), every number the sameΘ(n log⁡2 n)\Theta(n \,\log_2\, n), shuffled; measured, no formula worked out hereΘ(n log⁡2 n)\Theta(n \,\log_2\, n), the dearest row; this page finds it only for short rows, by trying every ordera few places, however long the rownoyesyou need a sort with no slow row and no second row, and equal items need not keep their order
counting sortΘ(n)\Theta(n) steps, every row alikeΘ(n)\Theta(n) stepsΘ(n)\Theta(n) steps, every row alikea second row of n places and 10 talliesyesnothe numbers are small whole numbers, such as ratings from 0 to 9, and equal ones must keep their order
radix sortΘ(n)\Theta(n) placings, every number below 10Θ(n)\Theta(n) placings, between the best and the worst, as every order costs the sameΘ(n)\Theta(n) placings, three passes for numbers up to 999a second row of n places and 10 talliesyesnomany whole numbers with few digits, such as numbers from 0 to 999
extra memory:
the room it needs on top of the input itself, while it runs.
keeps equal items in order:
people sorted by age keep the order they arrived in within each age; in general, two items equal in what is being sorted come out in the order they went in.
works in place:
it rearranges the input where it stands, with only a few spare places, rather than building a copy; a different sense from a number being in place, in its final position.

race them on one row of your own