Skip to content

Quick sort

ordering

Level 2 of 3

Also called Partition-exchange sort.

how it works

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

Quick sort takes the last number of the part as its pivot. A split looks at each number but the pivot, from the left. A smaller number swaps with the first number just after the small side, so the small side grows by one. A number equal to the pivot counts as not smaller. Then the pivot swaps in just after the small side, and it is placed: nothing bigger stands before it and nothing smaller after. The numbers on each side make a part, which waits on a list to be split the same way. A part of one number is placed as it is. Sorting by splitting into smaller sorts of the same kind is called divide and conquer.

3010402025pivot: the last number3010402025not smaller: stays1030402025smaller: swapped left1030402025not smaller: stays1020403025smaller: swapped left1020253040pivot placed
One split of 30, 10, 40, 20, 25, a row for each step. The triangle marks the number compared with the pivot 25, and the rule under the row is the small side.
level04273118562312491427311823124956271231182342495637123118234249564712182331424956
Every split of 42, 7, 31, 18, 56, 23, 12, 49. 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 39 steps, the steps between them left for the watch page
  1. step 2 of 39

    427311856231249

    Sort the part from place 1 to place 8. Its last number, 49, is the pivot: smaller numbers go to its left.

    what it remembers to know where it is
    pivot
    49
    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 7 of 39

    427311856231249

    56 is not smaller than the pivot 49, so it stays on the big side.

    what it remembers to know where it is
    pivot
    49
    part starts at place
    1
    part ends at place
    8
    looking at place
    5

    watch from here

  3. step 9 of 39

    427311823561249

    Swap 23 onto the small side, and 56 goes where 23 was.

    what it remembers to know where it is
    pivot
    49
    part starts at place
    1
    part ends at place
    8
    looking at place
    6

    watch from here

  4. step 12 of 39

    427311823124956

    Swap the pivot 49 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
    49
    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 21 of 39

    712311823424956

    Swap the pivot 12 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
    12
    part starts at place
    1
    part ends at place
    6
    looking at place
    not yet

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

    watch from here

  6. step 39 of 39

    712182331424956

    In order, after 17 comparisons and 7 swaps.

    what it remembers to know where it is
    pivot
    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 10
  2. a part of one number is in placePython lines 13 and 14
  3. take the part's last number as the pivotPython line 16
  4. look at each other number in the part, from the leftPython line 18
  5. if it is smaller than the pivot, swap it onto the small sidePython lines 17, 19, 20 and 21
  6. swap the pivot in just after the small side, where it staysPython lines 23 and 24
  7. sort the part on its left, then the part on its rightPython lines 11, 12, 25 and 26
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.

def quick_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    Each part of the list is split round its last number, the pivot: every
    number smaller than the pivot 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 of the pivot is sorted the same way, the left one first.
    The parts still to sort wait on a list of their own.
    """
    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

        pivot = numbers[high]  # the part's last number is the pivot
        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. A row already in order climbs two steps up for each step across: ten times the numbers, a hundred times the comparisons. The cheapest and the shuffled rows climb only a little more than one step.

comparisons, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

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

  • already in order, one of the dearest rowssolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • shuffled, the average over every order of different numbers, each order as likelysolid where measured by running it; dashed where its formula carries it on to ten million
  • the cheapest row, every pivot the middle in size of its partsolid where measured by running it; dashed where its formula carries it on to ten million
what a dearest row costs, at a billion comparisons a second
nncomparisonstime
1,000499,500about 500 microseconds
100,0004,999,950,000about 5 seconds
10,000,00049,999,995,000,000about 14 hours

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.

"""Count quick sort's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it prints the comparisons
on a row in order, on the cheapest row, and the average over 20 shuffles.
The counts are the same on any computer; only the time taken differs.
"""
import random


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 quick_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    Each part of the list is split round its last number, the pivot: every
    number smaller than the pivot 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 of the pivot is sorted the same way, the left one first.
    The parts still to sort wait on a list of their own.
    """
    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

        pivot = numbers[high]  # the part's last number is the pivot
        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


def cheapest(n, first=1):
    """The numbers first to first + n - 1, so every pivot is the middle in size."""
    if n <= 0:
        return []
    if n == 1:
        return [first]
    left = (n - 1) // 2
    pivot = first + left
    right = cheapest(n - 1 - left, pivot + 1)
    # the split moves the right part's first number to its end, so start it turned
    return cheapest(left, first) + right[-1:] + right[:-1] + [pivot]


def count(row):
    """How many comparisons quick sort makes on this row."""
    Counted.comparisons = 0
    quick_sort([Counted(x) for x in row])
    return Counted.comparisons


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

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

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

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

  • already in order, one of the dearest rowssolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the room
  • shuffled, the average over every order of different numbers, each order as likelypoints only, each measured by a real run, since no single formula for the extra memory of this row is worked out here
  • the cheapest row, every pivot the middle in size of its partpoints 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 same splits cost little or much, depending on the row.

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
bestthe cheapest row, every pivot the middle in size of its partaverageshuffled, the average over every order of different numbers, each order as likelyworstalready in order, one of the dearest rows
comparisons(n+1)L−2L+1+2(n + 1)L - 2^{L + 1} + 22(n+1)H(n)−4n2(n + 1)H(n) - 4nn(n−1)2\frac{n(n - 1)}{2}
how the comparisons grow in each case
tight, Θ\ThetaΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2)
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n)O(n log⁡2 n)O(n \,\log_2\, n)O(n2)O(n^2)
floor, Ω\OmegaΩ(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n2)\Omega(n^2)

extra memory: 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 row

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

levelcomparisons013265784711324578652123456871312345678013
The cheapest row of 8. Every pivot is the middle in size of its part, so the parts halve. 7 + 5 + 1 = 13 comparisons, and the formula gives 9 times 3, less 16, plus 2, which is 13.
levelcomparisons01020304050607080711020304050607080621020304050607080531020304050607080441020304050607080351020304050607080261020304050607080171020304050607080028
A row in order. Each pivot is the biggest left, so each part is only one shorter. 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28 comparisons, and 8 times 7 over 2 is 28.

where the formula comes from

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

Why does a row in order cost n(n−1)2\frac{n(n - 1)}{2} comparisons, the most any row can?
  1. 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.

  2. the move: see a row in order split

    the line:
    in order, a split leavesone part of m−1 numbers,still in order\begin{gathered} \text{in order, a split leaves} \\ \text{one part of } m - 1 \text{ numbers,} \\ \text{still in order} \end{gathered}
    levelcomparisons0123454112345321234523123451412345010
    A row in order of 5. Each part is one shorter than the last. 4 + 3 + 2 + 1 = 10 comparisons.

    why it is allowed: The pivot, the last number, is the biggest. So every other number is smaller and stays on its left, in order, and nothing goes right.

  3. the move: add up the splits

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

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

  4. the move: add the counting numbers

    the line:
    W=(n−1)((n−1)+1)2W = \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:
    W=n(n−1)2W = \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: no row costs more

    the line:
    each pair meets at most once,so no row costs more than W\begin{gathered} \text{each pair meets at most once,} \\ \text{so no row costs more than } W \end{gathered}

    why it is allowed: Two numbers meet only when one is the pivot, which then stays outside both parts, so they never meet again. On a row in order every pair meets: the bigger of the two is a pivot first, with the smaller still in its part. So WW counts every pair once, and no row can count more. In the picture, 5 numbers make 10 pairs.

  7. the move: a ceiling

    the line:
    W≤n22W \le \frac{n^2}{2}

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

  8. the move: read it as a bound

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

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

  9. the move: a floor

    the line:
    W≥n24 for n≥2W \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.

  10. the move: read it as a bound

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

    why it is allowed: By line 9, WW never drops below a quarter of n2n^2.

  11. the move: ceiling and floor together

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

    why it is allowed: Lines 8 and 10 bound WW by the same growth, n2n^2.

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

Why can no row cost fewer than (n+1)L−2L+1+2(n + 1)L - 2^{L + 1} + 2 comparisons, and which row costs just that?
  1. the move: count a level

    the line:
    a level compares every numberit leaves still waiting\begin{gathered} \text{a level compares every number} \\ \text{it leaves still waiting} \end{gathered}
    levelcomparisons013265784711324578652123456871312345678013
    The cheapest row of 8, its levels placing 1, 2 and 4 numbers, then the last one.

    why it is allowed: A split compares every number of its part but the pivot, which it places. A part of one number is placed with no comparison. In the picture, level 0 leaves 7 numbers waiting and makes 7 comparisons; level 1 leaves 5 and makes 5.

  2. the move: count what a level places

    the line:
    level d places at most 2d numbers\text{level } d \text{ places at most } 2^d \text{ numbers}

    why it is allowed: Each part places one number and makes at most two parts. So level 0 has 1 part, level 1 at most 2, level 2 at most 4, and so on.

  3. the move: count what still waits

    the line:
    after level d, at leastn−(1+2+⋯+2d)numbers still wait\begin{gathered} \text{after level } d, \text{ at least} \\ n - (1 + 2 + \dots + 2^d) \\ \text{numbers still wait} \end{gathered}

    why it is allowed: By line 2, levels 0 to dd place at most 1+2+⋯+2d1 + 2 + \dots + 2^d numbers between them.

  4. the move: see the cheapest row fill its levels

    the line:
    with every pivotthe middle in size,levels 0 to L−1 are full\begin{gathered} \text{with every pivot} \\ \text{the middle in size,} \\ \text{levels } 0 \text{ to } L - 1 \text{ are full} \end{gathered}

    why it is allowed: Full means a level places all the numbers line 2 allows. Count gaps: a part has one gap more than it has numbers, one before each number and one after the last. A split keeps the gaps: 3 numbers have 4, and split round the middle one they leave 1 and 1, with 2 gaps each. A middle pivot shares the gaps as evenly as can be. So each part at level dd gets n+1n + 1 shared by 2d2^d, rounded down or up. Up to level L−1L - 1 that share is more than 2, since 2L2^L is at most nn. So each part keeps at least 2 gaps, at least one number to place. In the picture, 9 gaps become 4 and 5, then 2, 2, 2 and 3.

  5. the move: see the rest cost nothing

    the line:
    level L places the restwith no comparison\begin{gathered} \text{level } L \text{ places the rest} \\ \text{with no comparison} \end{gathered}

    why it is allowed: At level LL, n+1n + 1 shared by 2L2^L is at most 2, since nn is less than 2L+12^{L + 1}. So each part there holds one number or none. In the picture, level 3 places the 8 alone.

  6. the move: see such a row for every n

    the line:
    such a row exists for every n\text{such a row exists for every } n

    why it is allowed: Put the middle number last and build each side the same way. The split keeps the small side as it is, and the pivot swaps with the big side's first number, which goes to the end. So write the big side with its last number first: to get 5, 7, 8, 6 after the split, write 6, 5, 7, 8. For 8 numbers: 1, 3, 2, then 6, 5, 7, 8, then 4, as in the picture.

  7. the move: add the levels

    the line:
    B=(n−1)+(n−(1+2))+…+(n−(1+2+⋯+2L−1))\begin{gathered} B = (n - 1) + \bigl(n - (1 + 2)\bigr) \\ + \dots \\ + \bigl(n - (1 + 2 + \dots + 2^{L - 1})\bigr) \end{gathered}

    why it is allowed: BB is the comparisons on the cheapest row. By lines 1 and 3, no row's levels 0 to L−1L - 1 compare fewer than these. By lines 4 to 6, the row with every pivot in the middle compares just these.

  8. the move: add each doubling

    the line:
    B=(n−1)+(n−3)+(n−7)+⋯+(n−(2L−1))\begin{gathered} B = (n - 1) + (n - 3) + (n - 7) \\ + \dots + \bigl(n - (2^L - 1)\bigr) \end{gathered}
    where does this come from?
    question 1 of the page doubling and halving sumsAdd 1+2+4+⋯+2n1 + 2 + 4 + \dots + 2^n. What is the total?
    1. the move: name the sum

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

      why it is allowed: Let SS be the doubling sum up to 2n2^n. For nn as 3, it is 1 + 2 + 4 + 8.

    2. the move: double both sides

      the line:
      2S=2+4+8+⋯+2n+12S = 2 + 4 + 8 + \dots + 2^{n + 1}

      why it is allowed: Each term doubled is the next one along, and 2n2^n becomes 2n+12^{n + 1}. Doubling both sides keeps them equal. The plan: the two sums share all but their ends.

    3. the move: take line 1 away

      the line:
      2S−S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} 2S - S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Take SS from both sides of line 2. On the right, write SS out as line 1 does.

    4. the move: tidy the left side

      the line:
      S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Two lots of SS less one lot is one lot.

    5. the move: cancel what both brackets share

      the line:
      S=2n+1−1S = 2^{n + 1} - 1
      when n is 3124816
      first bracket24816
      second bracket1248
      left overtake away 116
      Line 4 when nn is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15.

      why it is allowed: Every term from 2 to 2n2^n is in both brackets and cancels, leaving 2n+12^{n + 1} less 1.

    6. the move: the terms before the last

      the line:
      1+2+⋯+2n−1=2(n−1)+1−1\begin{gathered} 1 + 2 + \dots + 2^{n - 1} \\ = 2^{(n - 1) + 1} - 1 \end{gathered}

      why it is allowed: The sum of line 5 stopping one term sooner: line 5 with n−1n - 1 for nn. For 3, it is 1 + 2 + 4. At nn as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.

    7. the move: tidy the power

      the line:
      2(n−1)+1−1=2n−12^{(n - 1) + 1} - 1 = 2^n - 1

      why it is allowed: One more than n−1n - 1 is nn. For 3, 1 + 2 + 4 is 7, one less than 8.

    8. the move: read it

      the line:
      one less thanthe next term,under twice the last\begin{gathered} \text{one less than} \\ \text{the next term,} \\ \text{under twice the last} \end{gathered}

      why it is allowed: By lines 6 and 7, the terms before the last add to one less than it: the last outweighs them all. By line 5 the sum is under 2n+12^{n + 1}, twice the last.

    the whole page: doubling and halving sums

    why it is allowed: The doublings 1, 2, 4 and on add up to one less than the next doubling, as the fold shows. So 1 + 2 is 3, and 1 + 2 + 4 is 7. For 8 numbers, L is 3 and B is 7 + 5 + 1, which is 13.

  9. the move: write each term with n + 1

    the line:
    B=(n+1−2)+(n+1−4)+⋯+(n+1−2L)\begin{gathered} B = (n + 1 - 2) + (n + 1 - 4) \\ + \dots + (n + 1 - 2^L) \end{gathered}

    why it is allowed: Taking away one less than a power of 2 is taking away the power and adding 1, so n−3n - 3 is n+1−4n + 1 - 4. There are LL terms.

  10. the move: gather the n + 1s

    the line:
    B=(n+1)L−(2+4+⋯+2L)B = (n + 1)L - (2 + 4 + \dots + 2^L)

    why it is allowed: The LL terms of line 9 each hold one n+1n + 1.

  11. the move: add the doublings again

    the line:
    B=(n+1)L−(2L+1−2)B = (n + 1)L - (2^{L + 1} - 2)

    why it is allowed: By the fold at line 8, the doublings from 1 add up to one less than the next doubling. Here the first 1 is missing, so it is two less. For 8 numbers, 2 + 4 + 8 is 14, which is 16 less 2.

  12. the move: open the bracket

    the line:
    B=(n+1)L−2L+1+2B = (n + 1)L - 2^{L + 1} + 2

    why it is allowed: Taking away a bracket takes away each thing in it. For 8 numbers, 9 times 3, less 16, plus 2, is 13, as in the picture.

  13. the move: a ceiling

    the line:
    B≤nLB \le nL

    why it is allowed: Each of the LL terms of line 9 is n+1n + 1 less a power of 2, at least 2, so each is less than nn.

  14. the move: a simpler ceiling

    the line:
    B≤n log⁡2 nB \le n \,\log_2\, n

    why it is allowed: LL is at most log⁡2 n\log_2\, n.

  15. the move: read it as a bound

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

    why it is allowed: By line 14.

  16. the move: a floor

    the line:
    B≥(L−1)n2+1 for n≥2B \ge (L - 1)\frac{n}{2} + 1 \text{ for } n \ge 2

    why it is allowed: 2L2^L is at most nn, so 2L−12^{L - 1} is at most half of nn. So each term of line 9 but the last is more than half of nn, and the last is at least 1. From 2 numbers on, line 9 has at least one term. For 8 numbers, 4 is half of 8.

  17. the move: leave out the 1

    the line:
    B≥(L−1)n2B \ge (L - 1)\frac{n}{2}

    why it is allowed: Taking 1 away from the floor of line 16 leaves a floor.

  18. the move: a floor with logs only

    the line:
    B≥(log⁡2 n−2)n2B \ge (\log_2\, n - 2)\frac{n}{2}

    why it is allowed: LL is the whole part of log⁡2 n\log_2\, n, so it is more than log⁡2 n\log_2\, n less 1, and L−1L - 1 is more than log⁡2 n−2\log_2\, n - 2.

  19. the move: what 8 numbers allow

    the line:
    log⁡2 n−2≥13 log⁡2 n for n≥8\log_2\, n - 2 \ge \frac{1}{3}\,\log_2\, n \text{ for } n \ge 8

    why it is allowed: From 8 numbers on, log⁡2 n\log_2\, n is at least 3, so 2 is at most two thirds of it, and taking 2 away leaves at least a third. At 8, 3 less 2 is 1, exactly a third of 3.

  20. the move: a simpler floor

    the line:
    B≥n log⁡2 n6 for n≥8B \ge \frac{n \,\log_2\, n}{6} \text{ for } n \ge 8

    why it is allowed: Put line 19 into line 18.

  21. the move: read it as a bound

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

    why it is allowed: By line 20.

  22. the move: ceiling and floor together

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

    why it is allowed: Lines 15 and 21 bound BB by the same growth, n log⁡2 nn \,\log_2\, n.

try it with a small nn: at n=8n = 8, line 7 gives B=13B = 13, which you can work out by hand

Why does a shuffled row cost 2(n+1)H(n)−4n2(n + 1)H(n) - 4n comparisons on average?
  1. the move: name the numbers

    the line:
    the numbers are 1,2,…,nin some order\begin{gathered} \text{the numbers are } 1, 2, \dots, n \\ \text{in some order} \end{gathered}

    why it is allowed: Only the order of the numbers matters to the splits, so any nn different numbers act like 1 to nn.

  2. the move: watch two numbers

    the line:
    until one of the numbersfrom i to j is a pivot,they all stay in one part\begin{gathered} \text{until one of the numbers} \\ \text{from } i \text{ to } j \text{ is a pivot,} \\ \text{they all stay in one part} \end{gathered}

    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.

  3. the move: a number between parts them

    the line:
    if the first of themto be a pivot is betweeni and j, they never meet\begin{gathered} \text{if the first of them} \\ \text{to be a pivot is between} \\ i \text{ and } j \text{, they never meet} \end{gathered}
    level0516243112354621235463123456
    The yellow triangles follow 2 and 5. The 3, between them, is the first of 2 to 5 to be a pivot, so they part without meeting.

    why it is allowed: That pivot sends ii left and jj right, into different parts, and it is neither of them. In the picture, the 3 parts 2 and 5.

  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}
    level0316245131245623124563123456
    The same shuffle with the 3 and the 5 traded. Now 5 is the first of 2 to 5 to be a pivot, and its split compares 2 with it.

    why it is allowed: 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. In the picture, 5 comes first and meets 2.

  5. the move: see each come first equally often

    the line:
    they meet in 2 of every j−i+1shuffles\begin{gathered} \text{they meet in 2 of every } j - i + 1 \\ \text{shuffles} \end{gathered}
    orderfirst pivot1 and 2 meet1 and 3 meet2 and 3 meetcomparisons
    1, 2, 331113
    2, 1, 331113
    1, 3, 221012
    3, 1, 221012
    2, 3, 111113
    3, 2, 111113
    in all64616
    Every order of 1, 2 and 3, each as likely, with a 1 where a pair meets. A row's comparisons are its 1s added up.

    why it is allowed: Trade the places of two numbers from ii to jj, as the pictures at lines 3 and 4 trade the 3 and the 5. Every split before one of them is a pivot stays the same. The first of them to be a pivot is taken from the same place, now holding the other number. So each of the j−i+1j - i + 1 numbers comes first equally often. By lines 3 and 4, the pair meets when it is ii or jj. In the table, each of 1, 2 and 3 comes first in 2 of the 6 orders, so 1 and 3 meet in 4.

  6. the move: count the pairs k apart

    the line:
    n−k pairs stand k apart,each meeting in 2k+1of the shuffles\begin{gathered} n - k \text{ pairs stand } k \text{ apart,} \\ \text{each meeting in } \frac{2}{k + 1} \\ \text{of the shuffles} \end{gathered}

    why it is allowed: Two numbers stand kk apart when the bigger is the smaller plus kk. Each of 1, 2, and on up to n−kn - k has a partner kk above it. With 4 numbers, 3 pairs stand 1 apart. From ii to jj there are then k+1k + 1 numbers, so line 5 gives 2 in k+1k + 1.

  7. the move: average pair by pair

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

    why it is allowed: AA is the comparisons averaged over every shuffle. A shuffle's comparisons are the pairs that meet in it, each once by line 4. Adding every shuffle's comparisons counts each pair once for each shuffle where it meets. Dividing by the shuffles gives each pair's share, from line 6. In the table: 6 + 4 + 6 is 16 comparisons over 6 orders, or 1, plus 2 thirds, plus 1.

  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 less 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: gather the terms

    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, 2 times 4 times 11 sixths, less 12, is 16 over 6, the table's average.

  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.

  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.

  21. the move: a floor from the cheapest row

    the line:
    A≥n log⁡2 n6 for n≥8A \ge \frac{n \,\log_2\, n}{6} \text{ for } n \ge 8

    why it is allowed: No shuffle costs less than the cheapest row, so neither does their average. The cheapest row costs at least this, by line 20 of the question on the cheapest row, in section 4 of the learn page.

  22. 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 21.

  23. 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 22 bound AA by the same growth, n log⁡2 nn \,\log_2\, n.

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

How many memory places do the waiting parts take at once on a row in order?
  1. the move: the list of waiting parts

    the line:
    a split takes its part off the listand puts its two parts on\begin{gathered} \text{a split takes its part off the list} \\ \text{and puts its two parts on} \end{gathered}
    afterparts waitingparts
    the startplaces 1 to 51
    splitting 1 to 5an empty part, places 1 to 42
    splitting 1 to 42 empty parts, places 1 to 33
    splitting 1 to 33 empty parts, places 1 to 24
    splitting 1 to 24 empty parts, place 15
    A row in order of 5. Each split leaves an empty right part waiting, so the list grows by one part each time, to 5 parts.

    why it is allowed: Each waiting part takes two memory places, one for where it starts in the row and one for where it ends. The left part is taken off first. An empty part is put on too, and dropped when it is taken off.

  2. the move: in order, the list only grows

    the line:
    in order, each split puts onan empty right part,which waits to the end\begin{gathered} \text{in order, each split puts on} \\ \text{an empty right part,} \\ \text{which waits to the end} \end{gathered}

    why it is allowed: By line 2 of the first ladder, nothing goes right of a pivot, and the left part is taken off next.

  3. the move: count the places

    the line:
    M=2(1+(n−1))M = 2\bigl(1 + (n - 1)\bigr)

    why it is allowed: MM is the most memory places taken at once. The list starts with the whole row. A row in order takes n−1n - 1 splits, by line 3 of the first ladder, and by lines 1 and 2 each adds a part, two places each.

  4. the move: tidy

    the line:
    M=2nM = 2n

    why it is allowed: For 5 numbers, 5 parts, 10 places.

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

count it yourself

Count every comparison on the cheapest row of 5 numbers. For 5 numbers LL is 2, so the formula gives 6 times 2, less 8, plus 2, which is 6.

2, 1, 4, 5, 3, every step written down
stepthe rowwhat happenscomparisonsswaps
12, 1, 4, 5, 3There are 5 numbers in a row. Sort the whole row as one part.2, 1, 4, 5, 300
22, 1, 4, 5, 3Sort the part from place 1 to place 5. Its last number, 3, is the pivot: smaller numbers go to its left.2, 1, 4, 5, 300
32, 1, 4, 5, 32 is smaller than the pivot 3, and it already stands at the end of the small side.2, 1, 4, 5, 310
42, 1, 4, 5, 31 is smaller than the pivot 3, and it already stands at the end of the small side.2, 1, 4, 5, 320
52, 1, 4, 5, 34 is not smaller than the pivot 3, so it stays on the big side.2, 1, 4, 5, 330
62, 1, 4, 5, 35 is not smaller than the pivot 3, so it stays on the big side.2, 1, 4, 5, 340
72, 1, 3, 5, 4Swap the pivot 3 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.2, 1, 3, 5, 441
82, 1, 3, 5, 42 numbers lie to its left and 2 to its right: sort each side the same way, the left one first.2, 1, 3, 5, 441
92, 1, 3, 5, 4Sort the part from place 1 to place 2. Its last number, 1, is the pivot: smaller numbers go to its left.2, 1, 3, 5, 441
102, 1, 3, 5, 42 is not smaller than the pivot 1, so it stays on the big side.2, 1, 3, 5, 451
111, 2, 3, 5, 4Swap the pivot 1 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.1, 2, 3, 5, 452
121, 2, 3, 5, 4Nothing lies to its left and 1 to its right: sort each side the same way, the left one first.1, 2, 3, 5, 452
131, 2, 3, 5, 42 is alone in its part, so it is in place for good.1, 2, 3, 5, 452
141, 2, 3, 5, 4Sort the part from place 4 to place 5. Its last number, 4, is the pivot: smaller numbers go to its left.1, 2, 3, 5, 452
151, 2, 3, 5, 45 is not smaller than the pivot 4, so it stays on the big side.1, 2, 3, 5, 462
161, 2, 3, 4, 5Swap the pivot 4 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.1, 2, 3, 4, 563
171, 2, 3, 4, 5Nothing lies to its left and 1 to its right: sort each side the same way, the left one first.1, 2, 3, 4, 563
181, 2, 3, 4, 55 is alone in its part, so it is in place for good.1, 2, 3, 4, 563
191, 2, 3, 4, 5In order, after 6 comparisons and 3 swaps.1, 2, 3, 4, 563

In all, 6 comparisons. The formula from section 4, (n+1)L−2L+1+2(n + 1)L - 2^{L + 1} + 2, gives B=6B = 6 at n=5n = 5: the same.

where you meet it

Quick sort, with a few guards added, is inside many standard sorts.

  • the C++ library's sort

    C++ is a programming language. In the library that comes with the GNU compiler, its standard sort, std::sort, is introsort. It splits like quick sort, taking as pivot the middle in size of the part's second, middle and last numbers. If the parts go more than twice LL levels deep, it switches to heap sort, which has no bad row. Insertion sort finishes stretches of 16 or fewer.

    source: the GNU C++ library's stl_algo.h (__sort, __introsort_loop, __move_median_to_first, __final_insertion_sort) and stl_algobase.h (__lg), GCC 15. Heap sort having no bad case, the books' volume one, chapter 11

  • finding the middle value

    The same library's std::nth_element finds the number that belongs at one place, such as the middle, without sorting the rest. It splits like quick sort, but then works on only the part holding that place.

    source: the GNU C++ library's file stl_algo.h, as shipped with GCC 15, the parts called nth_element and __introselect

what is used instead

This page's quick sort is the plain one. Real sorts add guards, as Sebastian Bourges' books, Algorithmic Thinking Without the Jargon, list in volume one, chapter 11. A random or middle pivot keeps a row in order from being the dearest. Insertion sort finishes the short parts. Sorting the smaller part first keeps the list of waiting parts short. Quick sort can swap equal numbers: sorting 4, 4, 9 ends with the two 4s swapped, as the second 4 is a pivot and swaps in front of the first. When equal items must keep the order they came in, merge sort is used instead.

how it compares

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 sortrandomised quick sortmerge sortheap sortquick sort10110210310410510610710810910101011101210131014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortshell sortrandomised quick sortmerge sortheap sortquick 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