Skip to content

Quickselect

finding

Level 3 of 3

Also called Hoare's selection algorithm.

how it works

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

Quickselect finds the number that would stand at place kk if the row were in order, without sorting it. It splits the row as quick sort does. The last number is the pivot; smaller numbers swap onto the small side at the left, and the pivot swaps in just after them. If it lands at place kk, it is the answer. If not, only one side can hold place kk. The pivot and the other side are ruled out, and the kept side is split again. A part of one number is the answer. The books' volume one, chapter 13 names it quickselect, or Hoare's Find.

427311856231249pivot: the last number427311856231249smaller: already left427311856231249smaller: already left427311856231249smaller: already left427311856231249smaller: already left427311856231249not smaller: stays427311823561249smaller: swapped left427311823125649smaller: swapped left427311823124956pivot placed
The first split, looking for place 4. The triangle marks the number compared with the pivot 49, and a line marks the end of the small side. Every number left of 49 is smaller, so 49 is at place 7 in order, and place 4 must be on its left.
levelcomparisonsplace 404273118562312497142731182312495652712311823424956337123118234249562found71218233142495617
Every split of the same search, each part as it starts. Struck grey squares are ruled out; the caret marks place 4. 7 + 5 + 3 + 2 = 17 comparisons, and the last row finds 23.
The middle of eight: 8 moments of its 35 steps, the steps between them left for the watch page
  1. step 2 of 35

    427311856231249

    Search 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
    place wanted
    4
    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 8 of 35

    427311856231249

    23 is smaller than the pivot 49, so it goes onto the small side.

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

    watch from here

  3. step 12 of 35

    427311823124956

    Swap the pivot 49 in just after the small side, at place 7. That is where it would stand if the row were in order.

    what it remembers to know where it is
    place wanted
    4
    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

  4. step 13 of 35

    427311823124956

    Place 4 lies to the left of place 7, so rule out the pivot 49 and every number to its right.

    what it remembers to know where it is
    place wanted
    4
    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 35

    712311823424956

    Swap the pivot 12 in just after the small side, at place 2. That is where it would stand if the row were in order.

    what it remembers to know where it is
    place wanted
    4
    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 22 of 35

    712311823424956

    Place 4 lies to the right of place 2, so rule out the pivot 12 and every number to its left.

    what it remembers to know where it is
    place wanted
    4
    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

  7. step 28 of 35

    712311823424956

    Place 4 lies to the left of place 6, so rule out the pivot 42 and every number to its right.

    what it remembers to know where it is
    place wanted
    4
    pivot
    42
    part starts at place
    3
    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

  8. step 34 of 35

    712182331424956

    The pivot 23 stands at place 4, the place wanted, so it is the number wanted.

    what it remembers to know where it is
    place wanted
    4
    pivot
    23
    part starts at place
    3
    part ends at place
    5
    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. the part to search is the whole rowPython lines 10 and 11
  2. a part of one number holds the number wantedPython lines 12 and 28
  3. take the part's last number as the pivotPython line 13
  4. look at each other number in the part, from the leftPython line 15
  5. if it is smaller than the pivot, swap it onto the small sidePython lines 14, 16, 17 and 18
  6. swap the pivot in just after the small sidePython line 21
  7. if the pivot stands at the place wanted, it is the number wantedPython lines 22 and 23
  8. otherwise keep only the side holding the place wantedPython lines 24, 25, 26 and 27
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 quickselect(numbers, k):
    """Find the number that would stand at place k if the list were in order.

    Places count from 1, the smallest first. The list itself is
    rearranged. Each part is split round its last number, the pivot, as
    quick sort splits it: smaller numbers to its left, and the pivot just
    after them, where it would stand in order. Then only the side that
    holds place k is kept, and the other side is never looked at again.
    """
    want = k - 1  # the place wanted, counted from 0 as Python counts
    low, high = 0, len(numbers) - 1  # the part to search is the whole list
    while low < high:  # a part of one number holds the number wanted
        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, where it would stand in order
        numbers[small], numbers[high] = numbers[high], numbers[small]
        if small == want:  # it stands at the place wanted
            return numbers[small]
        if want < small:  # the place wanted is to its left:
            high = small - 1  # keep the left side only
        else:  # to its right:
            low = small + 1  # keep the right side only
    return numbers[low]

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. Asking a row in order for its smallest climbs two steps up for each step across: ten times the numbers, a hundred times the comparisons. The shuffled average and asking for the biggest climb 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

  • 1 to n in order, asking for the smallestsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • shuffled, averaged over every order of different numbers and every placesolid where measured by running it; dashed where its formula carries it on to ten million
  • 1 to n in order, asking for the biggestsolid 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 quickselect'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 asking for the biggest, the cheapest; on a row in order
asking for the smallest, the dearest; and the average over 200 shuffles,
each asking for a place picked at random, beside the formula for the exact
average over every order and every place. 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 quickselect(numbers, k):
    """Find the number that would stand at place k if the list were in order.

    Places count from 1, the smallest first. The list itself is
    rearranged. Each part is split round its last number, the pivot, as
    quick sort splits it: smaller numbers to its left, and the pivot just
    after them, where it would stand in order. Then only the side that
    holds place k is kept, and the other side is never looked at again.
    """
    want = k - 1  # the place wanted, counted from 0 as Python counts
    low, high = 0, len(numbers) - 1  # the part to search is the whole list
    while low < high:  # a part of one number holds the number wanted
        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, where it would stand in order
        numbers[small], numbers[high] = numbers[high], numbers[small]
        if small == want:  # it stands at the place wanted
            return numbers[small]
        if want < small:  # the place wanted is to its left:
            high = small - 1  # keep the left side only
        else:  # to its right:
            low = small + 1  # keep the right side only
    return numbers[low]


def count(row, k):
    """How many comparisons quickselect makes finding place k of this row."""
    Counted.comparisons = 0
    quickselect([Counted(x) for x in row], k)
    return Counted.comparisons


def exact_average(n):
    """The average over every order and every place: 3n + 13 - 8(n + 1)H(n)/n."""
    harmonic = sum(1 / i for i in range(1, n + 1))
    return 3 * n + 13 - 8 * (n + 1) * harmonic / n


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>6} {'biggest':>9} {'smallest':>10} {'shuffled':>10} {'formula':>10}")
    for n in [10, 100, 1000]:
        in_order = list(range(1, n + 1))
        runs = []
        for _ in range(200):
            row = list(range(1, n + 1))
            random.shuffle(row)
            runs.append(count(row, random.randint(1, n)))
        print(f"{n:>6} {count(in_order, n):>9} {count(in_order, 1):>10} {sum(runs) / 200:>10.1f} {exact_average(n):>10.1f}")

best, worst and average

One row can be the cheapest search or the dearest. It depends on the place asked for.

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
best1 to n in order, asking for the biggestaverageshuffled, averaged over every order of different numbers and every placeworst1 to n in order, asking for the smallest
comparisonsn−1n - 1, one split3n+13−8(n+1)H(n)n3n + 13 - \frac{8(n + 1)H(n)}{n}, under 3n3n; for 8 numbers 8 times 9 over 8 is 9 and H(8) is about 2.718, so 24 + 13 less 9 times 2.718, about 12.54n(n−1)2\frac{n(n - 1)}{2}, a split of each length
how the comparisons grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n)\Theta(n)Θ(n2)\Theta(n^2)
ceiling, OOO(n)O(n)O(n)O(n)O(n2)O(n^2)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n)\Omega(n)Ω(n2)\Omega(n^2)

extra memory: six boxes, the same however long the row, the five its storyboard shows under what it remembers and the small side's end. It rearranges the row itself

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

levelcomparisonsplace 807121823314249567found7121823314249567
A row in order, asking for place 8. The first pivot, 56, lands at place 8 at once. One split, 7 comparisons.
levelcomparisonsplace 10712182331424956717121823314249566271218233142495653712182331424956447121823314249563571218233142495626712182331424956177121823314249560found71218233142495628
The same row, asking for place 1. Each pivot is the biggest left, so each part is one shorter. 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28 comparisons, and 8 times 7 over 2 is 28.
place asked foraverage comparisons
110.56
212.25
313.39
413.95
513.95
613.39
712.25
810.56
Every order of 8 different numbers, 40,320 of them, asked for each place. That is 8 times 7, times 6, and on down to 1. In the same way 3 numbers have 3 times 2 times 1, 6 orders. The middle costs most.

where the formula comes from

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

Why does asking a row in order for its smallest cost n(n−1)2\frac{n(n - 1)}{2} comparisons, the most any search 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 asked for its smallest

    the line:
    each split keeps a partone shorter, still in order\begin{gathered} \text{each split keeps a part} \\ \text{one shorter, still in order} \end{gathered}
    levelcomparisonsplace 101234541123453212345231234514123450found1234510
    1 to 5 in order, asking for place 1. 4 + 3 + 2 + 1 = 10 comparisons, and the 1 left alone is the answer.

    why it is allowed: The pivot, the last number, is the biggest left. The rest are smaller and stay on its left, in order, and place 1 is there.

  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 asking 1 to nn in order for the smallest. By line 2 the parts hold nn, then n−1n - 1, down to 2. 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 or place costs more

    the line:
    each pair meets at most once,so no searchcosts more than W\begin{gathered} \text{each pair meets at most once,} \\ \text{so no search} \\ \text{costs more than } W \end{gathered}
    Row by row, 2, 3, 4 and 5 each pair with every smaller number, 1, 2, 3 and 4 squares. 5 numbers make 4 + 3 + 2 + 1 = 10 pairs, the same sum as WW.

    why it is allowed: Two numbers meet only when one is the pivot. That pivot is then found or ruled out, so it is in no later part, and the pair never meets again. As the square shows, nn numbers make 1, plus 2, and on up to n−1n - 1 pairs, line 3's sum backwards. So no search makes more than WW comparisons. Here every pair meets: the bigger is a pivot first, with the smaller still in its part.

  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. For 5, 10 is under 12.5.

  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 a half of n2n^2, and a half is the fixed multiple.

  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 a half of nn once nn is 2 or more. For 5, 10 is at least 6.25.

  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, and a quarter is the fixed multiple.

  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 search cost fewer than n−1n - 1 comparisons, and which costs just that?
  1. the move: price the first split

    the line:
    every search starts witha split of all n numbers\begin{gathered} \text{every search starts with} \\ \text{a split of all } n \text{ numbers} \end{gathered}

    why it is allowed: The part to search starts as the whole row. From 2 numbers on, it is split, and by line 1 of the first ladder that costs one fewer than nn.

  2. the move: see a search end at once

    the line:
    asking 1 to n in orderfor the biggest, the firstpivot is the answer\begin{gathered} \text{asking } 1 \text{ to } n \text{ in order} \\ \text{for the biggest, the first} \\ \text{pivot is the answer} \end{gathered}
    levelcomparisonsplace 50123454found123454
    1 to 5 in order, asking for place 5. The pivot 5 lands at place 5 and is the answer. One split, 4 comparisons.

    why it is allowed: The pivot, the last number, is nn, the biggest. Nothing is bigger, so it lands at place nn, the place wanted, and the search ends.

  3. the move: count it

    the line:
    B=n−1B = n - 1

    why it is allowed: BB is the fewest comparisons any row and place of nn numbers can cost. By line 1 no search costs fewer, and by line 2 this one costs just that. For 5 numbers, 4.

  4. the move: a ceiling

    the line:
    B≤nB \le n

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

  5. the move: read it as a bound

    the line:
    B∈O(n)B \in O(n)

    why it is allowed: By line 4.

  6. the move: a floor

    the line:
    B≥n2 for n≥2B \ge \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: From 2 numbers on, 1 is at most half of nn, so n−1n - 1 is at least the other half.

  7. the move: read it as a bound

    the line:
    B∈Ω(n)B \in \Omega(n)

    why it is allowed: By line 6.

  8. the move: ceiling and floor together

    the line:
    B∈Θ(n)B \in \Theta(n)

    why it is allowed: Lines 5 and 7 bound BB by the same growth, nn.

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

Why does a shuffled row cost 3n+13−8(n+1)H(n)n3n + 13 - \frac{8(n + 1)H(n)}{n} comparisons on average over every place, under 3n3n?
  1. the move: name the numbers

    the line:
    the numbers are 1 to nin some order, andthe number wanted is k\begin{gathered} \text{the numbers are } 1 \text{ to } n \\ \text{in some order, and} \\ \text{the number wanted is } k \end{gathered}
    orderplace 1place 2place 3
    1, 2, 3332
    2, 1, 3332
    3, 1, 2222
    1, 3, 2222
    2, 3, 1233
    3, 2, 1233
    in all141614
    Quickselect's comparisons on every order of 1, 2, 3, asked for each place. 14 + 16 + 14 is 44, over 18 searches.

    why it is allowed: Only the order by size matters to the splits: 42, 7, 31 splits exactly as 3, 1, 2 does. So any nn different numbers act like 1 to nn, and place kk wants kk itself.

  2. the move: draw the stretch

    the line:
    a pair i,j and the place kmake a stretch: from thesmaller of i,k to the bigger of j,k\begin{gathered} \text{a pair } i, j \text{ and the place } k \\ \text{make a stretch: from the} \\ \text{smaller of } i, k \text{ to the bigger of } j, k \end{gathered}
    123456wanted5 numbers
    1 to 6 by size. Triangles mark the pair 2 and 5, the ring place 1. The bracket is the stretch.

    why it is allowed: The plan: count comparisons by counting which pairs meet. Take two numbers, ii the smaller and jj the bigger.

  3. the move: the stretch stays together

    the line:
    until one of the stretch is a pivot,all of it stays in the part\begin{gathered} \text{until one of the stretch is a pivot,} \\ \text{all of it stays in the part} \end{gathered}

    why it is allowed: A pivot below the stretch or above it sends all of the stretch to one side. Place kk is in the stretch, so that side is the one kept.

  4. the move: an end comes first

    the line:
    if the first pivot from thestretch is i or j,they meet, once\begin{gathered} \text{if the first pivot from the} \\ \text{stretch is } i \text{ or } j \text{,} \\ \text{they meet, once} \end{gathered}
    levelplace 106234151234156found134256
    Asking 6, 2, 3, 4, 1, 5 for place 1. The triangles follow 2 and 5. The first pivot, 5, is one of them, so its split compares 2 with it.

    why it is allowed: By line 3 the other is still in its part, so the split compares them; by line 6 of the first ladder, only once.

  5. the move: a number between parts them

    the line:
    if the first pivot from thestretch lies between i and j,they never meet\begin{gathered} \text{if the first pivot from the} \\ \text{stretch lies between } i \text{ and } j, \\ \text{they never meet} \end{gathered}
    levelplace 106524131213456found123456
    Asking 6, 5, 2, 4, 1, 3 for place 1. The first pivot, 3, sends 2 left and 5 right, ruled out unmet.

    why it is allowed: Neither was a pivot before that one, and by line 3 both are in its part. That pivot sends them to different sides, and one side is ruled out, or that pivot is kk and the search ends.

  6. the move: the rest rule them out

    the line:
    if the first pivot from thestretch is between the pairand k, or is k and not oneof the pair, they never meet\begin{gathered} \text{if the first pivot from the} \\ \text{stretch is between the pair} \\ \text{and } k, \text{ or is } k \text{ and not one} \\ \text{of the pair, they never meet} \end{gathered}
    levelplace 106531421123645found123645
    Asking 6, 5, 3, 1, 4, 2 for place 1. The first pivot, 2, lies between place 1 and the pair 3 and 5, and rules both out unmet.
    12345both ruled outtheymeetkeptaparttheymeetwanted5 numbers
    The pair 3 and 5, place 1, stretch 1 to 5. Under each number, what happens if it is the first pivot from the stretch. 2 of these 5 make them meet.

    why it is allowed: That pivot rules both out together. Or that pivot is kk, found, and kk is neither of them, so neither is compared with the other.

  7. the move: see each come first equally often

    the line:
    in a stretch of s numbers, the pairmeets in 2 of every s shuffles\begin{gathered} \text{in a stretch of } s \text{ numbers, the pair} \\ \text{meets in 2 of every } s \text{ shuffles} \end{gathered}
    levelplace 10361245131245623124563123456found123456
    Asking 3, 6, 1, 2, 4, 5 for place 1, following 2 and 3, stretch 1 to 3. The pivots 5 and 4 lie above it. The third pivot, 2, is the first from the stretch, so 2 meets 3.
    levelplace 1036214513214562321456found123456
    The same row with 1 and 2 traded. The pivots 5 and 4 split it the same way. The third pivot stands in the same place, now 1, the place wanted. It is found, and 2 and 3 never meet.

    why it is allowed: In line 8's table, asking place 1, the first pivot from 1 to 3 is 3, 3, 2, 2, 1, 1, each first 2 times in 6, 1 in 3. The search cannot end while the stretch, 2 or more numbers, is all in the part, so one of them is always first. Now trade two numbers of the stretch. Before any of the stretch is a pivot, each pivot is above both or below both, by line 3, so each split moves them alike. So if one of the two came first, the other now does. Trading matches each shuffle with exactly one other, so each of the ss numbers comes first equally often, 1 in ss. By lines 4 to 6, two of them make the pair meet.

  8. the move: add each pair's share

    the line:
    the average comparisonsare the shares of shuffleseach pair meets in, added\begin{gathered} \text{the average comparisons} \\ \text{are the shares of shuffles} \\ \text{each pair meets in, added} \end{gathered}
    orderfirst pivot from 1 to 31 and 2 meet1 and 3 meet2 and 3 meetcomparisons
    1, 2, 331113
    2, 1, 331113
    3, 1, 221012
    1, 3, 221012
    2, 3, 111102
    3, 2, 111102
    in all64414
    Every order of 1, 2, 3 asked for place 1, a 1 where a pair meets. 1 and 3 meet when 1 or 3 is first from 1 to 3, 2 and 3 when 2 or 3 is. A row's 1s add up to its comparisons.

    why it is allowed: By line 6 of the first ladder, each pair meets at most once, so a search's comparisons are the pairs that meet in it. Averages add, as the expected-cost page shows in its pairs question, line 2. In the table the pairs' 1s, 6 + 4 + 4, and the orders' comparisons both add to 14. Over the 6 orders, 6 sixths, plus 4 sixths, plus 4 sixths, is 14 sixths, the average at place 1. 1 and 2, stretch 1 to 2, meet in all 6. 1 and 3, and 2 and 3, stretch 1 to 3, meet in 4, 2 in every 3, as line 7 says.

  9. the move: count the ways to a stretch

    the line:
    3s−4 pairs and placeshave the stretch 1 to s\begin{gathered} 3s - 4 \text{ pairs and places} \\ \text{have the stretch } 1 \text{ to } s \end{gathered}
    the pair at both ends, the place anywhere41234123412341234the smaller of the pair first, the place last212341234the place first, the bigger of the pair last2123412348in all: 3 times 4, less 4
    Every pair and place whose stretch is 1 to 4, a row each. The triangles mark the pair, the ring the place.

    why it is allowed: 1 and ss must each be one of the pair or the place; the place is one number, so the pair holds at least one end. The pair at both ends, the place anywhere: ss ways. 1 the pair's smaller and ss the place: the bigger is any of 2 up to ss less 1, ss less 2 ways. The place 1 and ss the pair's bigger: ss less 2 more. In all, 3s−43s - 4 pair and place choices; for ss of 4, 4 + 2 + 2 = 8, the picture's three groups. With 1, 2, 3, 3 + 1 + 1 is 5.

  10. the move: slide the stretch

    the line:
    n−s+1 stretches hold s numbers,each with 3s−4 pairs and places\begin{gathered} n - s + 1 \text{ stretches hold } s \text{ numbers,} \\ \text{each with } 3s - 4 \text{ pairs and places} \end{gathered}
    stretch12345
    1 to 3123
    2 to 4234
    3 to 5345
    Stretches of 3 among 5 numbers, a row each. They start at 1, 2 and 3, and n−s+1n - s + 1 is 5 less 3, plus 1, so 3 stretches.

    why it is allowed: A stretch of ss numbers starts at 1, 2, and on up to n−s+1n - s + 1, and sliding it changes nothing in line 9. With 1, 2, 3, stretches of 2 start at 1 and 2, of 3 at 1.

  11. the move: average pair by pair

    the line:
    A=1n∑s=2n(n−s+1)(3s−4)2sA = \frac{1}{n}\sum_{s = 2}^{n} (n - s + 1)(3s - 4)\frac{2}{s}
    ssstretchespair and place choicesshareproduct
    2222 over 24
    3152 over 310 thirds
    in all22 thirds
    The sum for 3 numbers, a row for each ss. 22 thirds over 3 places is 22 ninths, line 1's 44 over 18.

    why it is allowed: AA is the comparisons averaged over every shuffle and every place. By line 8, add every pair and place's share. Lines 9 and 10 count (n−s+1)(3s−4)(n - s + 1)(3s - 4) pairs and places for each ss, each meeting in 2 of every ss shuffles by line 7, and dividing by nn averages the places.

  12. the move: share out 2 over s

    the line:
    A=1n∑s=2n(n−s+1)(6−8s)A = \frac{1}{n}\sum_{s = 2}^{n} (n - s + 1)\Bigl(6 - \frac{8}{s}\Bigr)

    why it is allowed: (3s−4)(3s - 4) times 2 over ss is 6s6s over ss, less 8 over ss, which is 6 less 8 over ss. For ss of 2, 2 times 2 over 2 is 2, and 6 less 4 is 2.

  13. the move: multiply out, keeping n + 1 together

    the line:
    A=1n∑s=2n(6(n+1)−8(n+1)s−6s+8)\begin{gathered} A = \frac{1}{n}\sum_{s = 2}^{n} \Bigl(6(n + 1) \\ - \frac{8(n + 1)}{s} - 6s + 8\Bigr) \end{gathered}
    times66−8s-\frac{8}{s}
    n+1n + 16(n+1)6(n + 1)−8(n+1)s-\frac{8(n + 1)}{s}
    −s-s−6s-6s+8+8
    The four products. For 3 numbers and ss of 2, 24, less 16, less 12, plus 8 is 4, as 2 times 2 is.

    why it is allowed: Read n−s+1n - s + 1 as n+1n + 1, less ss, and multiply each by 6 less 8 over ss, as in the grid. ss times 8 over ss is 8.

  14. the move: add up each part

    the line:
    A=1n(6(n+1)(n−1)−8(n+1)∑s=2n1s−6∑s=2ns+8(n−1))\begin{gathered} A = \frac{1}{n}\Bigl(6(n + 1)(n - 1) - 8(n + 1)\sum_{s = 2}^{n} \frac{1}{s} \\ - 6\sum_{s = 2}^{n} s + 8(n - 1)\Bigr) \end{gathered}

    why it is allowed: ss takes n−1n - 1 values, 2 up to nn. A part that does not change with ss is added n−1n - 1 times. A multiplier on every term, such as 8(n+1)8(n + 1) or 6, comes out in front of the sum. For 3, ss is 2 and 3, and 6 times 4 added twice is 48.

  15. the move: add 2 up to n

    the line:
    A=1n(6(n+1)(n−1)−8(n+1)∑s=2n1s−6(n(n+1)2−1)+8(n−1))\begin{gathered} A = \frac{1}{n}\Bigl(6(n + 1)(n - 1) - 8(n + 1)\sum_{s = 2}^{n} \frac{1}{s} \\ - 6\Bigl(\frac{n(n + 1)}{2} - 1\Bigr) + 8(n - 1)\Bigr) \end{gathered}
    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 adds the whole numbers from 1 up to nn with two staircases, nn times n+1n + 1, halved. The sum here leaves out the 1. For 3, 2 + 3 is 5, which is 6 less 1.

  16. the move: name the harmonic sum

    the line:
    A=1n(6(n+1)(n−1)−8(n+1)(H(n)−1)−6(n(n+1)2−1)+8(n−1))\begin{gathered} A = \frac{1}{n}\Bigl(6(n + 1)(n - 1) \\ - 8(n + 1)\bigl(H(n) - 1\bigr) \\ - 6\Bigl(\frac{n(n + 1)}{2} - 1\Bigr) + 8(n - 1)\Bigr) \end{gathered}
    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 sum here is H(n)H(n), the harmonic sum, without its first 1. The fold shows how H(n)H(n) grows. For 3, a half and a third make 5 sixths, and H(3)H(3) is 1 + a half + a third, 11 sixths.

  17. the move: open the brackets

    the line:
    A=1n(6n2−6−8(n+1)H(n)+8n+8−3n2−3n+6+8n−8)\begin{gathered} A = \frac{1}{n}\Bigl(6n^2 - 6 \\ - 8(n + 1)H(n) + 8n + 8 \\ - 3n^2 - 3n + 6 \\ + 8n - 8\Bigr) \end{gathered}

    why it is allowed: Open line 16's four parts, a row each. (n+1)(n−1)(n + 1)(n - 1) is n2n^2 less 1. Taking 1 from H(n)H(n), −8(n+1)-8(n + 1) times −1-1 is plus 8 lots of n+1n + 1, which is 8n+88n + 8. 6 times half of n(n+1)n(n + 1) is 3 lots of n2n^2 and 3 of nn, and minus 6 times minus 1 is plus 6.

  18. the move: gather

    the line:
    A=3n2+13n−8(n+1)H(n)nA = \frac{3n^2 + 13n - 8(n + 1)H(n)}{n}
    part opened outn2n^2nnnumberH(n)H(n)
    6n2−66n^2 - 666−6-6
    −8(n+1)H(n)+8n+8-8(n + 1)H(n) + 8n + 88888−8(n+1)H(n)-8(n + 1)H(n)
    −3n2−3n+6-3n^2 - 3n + 6−3-3−3-366
    8n−88n - 888−8-8
    in all33131300−8(n+1)H(n)-8(n + 1)H(n)
    Line 17's four rows, sorted into columns. Each column adds up, and the plain numbers cancel.

    why it is allowed: Add each column of the grid.

  19. the move: divide by n

    the line:
    A=3n+13−8(n+1)H(n)nA = 3n + 13 - \frac{8(n + 1)H(n)}{n}

    why it is allowed: Divide each part by nn. For 3, 9 + 13 is 22, which is 198 ninths, and 8 times 4 times 11 sixths, over 3, is 176 ninths. 198 less 176 ninths is 22 ninths, as in line 11.

  20. the move: a ceiling from line 12

    the line:
    A≤1n∑s=2n6(n−s+1)A \le \frac{1}{n}\sum_{s = 2}^{n} 6(n - s + 1)

    why it is allowed: In line 12, each stretch's share, 6 less 8 over ss, is less than 6.

  21. the move: add the counting numbers

    the line:
    A≤6n⋅(n−1)n2A \le \frac{6}{n} \cdot \frac{(n - 1)n}{2}

    why it is allowed: As ss runs from 2 to nn, n−s+1n - s + 1 runs from n−1n - 1 down to 1. By the fold at line 15, those add up to n−1n - 1 times nn, halved. The 6 comes out in front, as in line 14.

  22. the move: tidy

    the line:
    A≤3(n−1)A \le 3(n - 1)

    why it is allowed: 6 over nn, times nn, halved, is 3. For 3 numbers that is 6, and the average is 22 ninths, about 2.44.

  23. the move: a simpler ceiling

    the line:
    A≤3nA \le 3n

    why it is allowed: n−1n - 1 is less than nn.

  24. the move: read it as a bound

    the line:
    A∈O(n)A \in O(n)

    why it is allowed: By line 23.

  25. the move: a floor from the first split

    the line:
    A≥n−1A \ge n - 1

    why it is allowed: Every search splits all nn numbers first, by line 1 of the second ladder, so their average does too.

  26. the move: a simpler floor

    the line:
    A≥n2 for n≥2A \ge \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: In line 25, from 2 numbers on, 1 is at most half of nn, so n−1n - 1 is at least the other half.

  27. the move: read it as a bound

    the line:
    A∈Ω(n)A \in \Omega(n)

    why it is allowed: By line 26.

  28. the move: ceiling and floor together

    the line:
    A∈Θ(n)A \in \Theta(n)

    why it is allowed: Lines 24 and 27 bound AA by the same growth, nn.

try it on small inputs: over the 6 orders of 1, 2, 3 and each of the 3 places, 18 searches, the average AA is about 2.44

count it yourself

Count every comparison asking 27, 35, 48, 14, 62 for place 3, written as the row, a semicolon, then the place. Each pivot is the biggest or the smallest left in its part, so each part is one shorter.

27, 35, 48, 14, 62; 3, every step written down
stepthe rowwhat happenscomparisonsswaps
127, 35, 48, 14, 62There are 5 numbers in a row. Find the number that would stand at place 3 if they were in order, smallest first.27, 35, 48, 14, 6200
227, 35, 48, 14, 62Search the part from place 1 to place 5. Its last number, 62, is the pivot: smaller numbers go to its left.27, 35, 48, 14, 6200
327, 35, 48, 14, 6227 is smaller than the pivot 62, and it already stands at the end of the small side.27, 35, 48, 14, 6210
427, 35, 48, 14, 6235 is smaller than the pivot 62, and it already stands at the end of the small side.27, 35, 48, 14, 6220
527, 35, 48, 14, 6248 is smaller than the pivot 62, and it already stands at the end of the small side.27, 35, 48, 14, 6230
627, 35, 48, 14, 6214 is smaller than the pivot 62, and it already stands at the end of the small side.27, 35, 48, 14, 6240
727, 35, 48, 14, 62The pivot 62 already stands just after the small side, at place 5, where it would stand if the row were in order.27, 35, 48, 14, 6240
827, 35, 48, 14, 62Place 3 lies to the left of place 5, so rule out the pivot 62 and every number to its right.27, 35, 48, 14, 6240
927, 35, 48, 14, 62Search the part from place 1 to place 4. Its last number, 14, is the pivot: smaller numbers go to its left.27, 35, 48, 14, 6240
1027, 35, 48, 14, 6227 is not smaller than the pivot 14, so it stays on the big side.27, 35, 48, 14, 6250
1127, 35, 48, 14, 6235 is not smaller than the pivot 14, so it stays on the big side.27, 35, 48, 14, 6260
1227, 35, 48, 14, 6248 is not smaller than the pivot 14, so it stays on the big side.27, 35, 48, 14, 6270
1314, 35, 48, 27, 62Swap the pivot 14 in just after the small side, at place 1. That is where it would stand if the row were in order.14, 35, 48, 27, 6271
1414, 35, 48, 27, 62Place 3 lies to the right of place 1, so rule out the pivot 14 and every number to its left.14, 35, 48, 27, 6271
1514, 35, 48, 27, 62Search the part from place 2 to place 4. Its last number, 27, is the pivot: smaller numbers go to its left.14, 35, 48, 27, 6271
1614, 35, 48, 27, 6235 is not smaller than the pivot 27, so it stays on the big side.14, 35, 48, 27, 6281
1714, 35, 48, 27, 6248 is not smaller than the pivot 27, so it stays on the big side.14, 35, 48, 27, 6291
1814, 27, 48, 35, 62Swap the pivot 27 in just after the small side, at place 2. That is where it would stand if the row were in order.14, 27, 48, 35, 6292
1914, 27, 48, 35, 62Place 3 lies to the right of place 2, so rule out the pivot 27 and every number to its left.14, 27, 48, 35, 6292
2014, 27, 48, 35, 62Search the part from place 3 to place 4. Its last number, 35, is the pivot: smaller numbers go to its left.14, 27, 48, 35, 6292
2114, 27, 48, 35, 6248 is not smaller than the pivot 35, so it stays on the big side.14, 27, 48, 35, 62102
2214, 27, 35, 48, 62Swap the pivot 35 in just after the small side, at place 3. That is where it would stand if the row were in order.14, 27, 35, 48, 62103
2314, 27, 35, 48, 62The pivot 35 stands at place 3, the place wanted, so it is the number wanted.14, 27, 35, 48, 62103
2414, 27, 35, 48, 62Found, after 10 comparisons and 3 swaps.14, 27, 35, 48, 62103

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

where you meet it

Two libraries hand you quickselect ready made, with guards against its worst case.

  • the C++ library's nth_element

    In the GNU compiler's C++ library, std::nth_element puts the number that belongs at one place, such as the middle, into that place. Like quickselect, it splits a part and keeps the side holding that place. Its pivot is the middle in size of three of the part's numbers, the second, the one halfway along and the last, for 8 numbers places 2, 5 and 8. On 42, 7, 31, 18, 56, 23, 12, 49 those are 7, 56 and 49, so the pivot is 49. To guard against a worst case that grows as n2n^2, as quickselect's does, after a set number of splits it switches to a heap. That number is the log of the row's length, rounded down, then doubled. For 8 numbers the log is 3, so 6 splits.

    source: the GNU C++ library's stl_algo.h as shipped with GCC 15, read offline, the parts called nth_element, __introselect, __unguarded_partition_pivot, __move_median_to_first and __heap_select; and stl_algobase.h, __lg

  • NumPy's partition

    NumPy is Python's library for rows of numbers. numpy.partition(row, 3) gives a copy of the row with the fourth smallest at index 3, counted from 0. With row as 42, 7, 31, 18, 56, 23, 12, 49, that is 23. Smaller numbers stand before it and the rest after, each side in no set order. Its way is introselect, which its documentation lists as linear at worst.

    source: the NumPy 2.3 reference, numpy.partition (opens in a new tab), read in NumPy 2.3.5

what is used instead

Sebastian Bourges' books, Algorithmic Thinking Without the Jargon, trace quickselect to Hoare's Algorithm 65, Find, printed in 1961 beside his quick sort (volume one, chapter 13). They put it in one line: "the second algorithm is the first one with a line deleted." The line deleted is the one that sorts the other side. The same chapter says when to reach for something else. For the whole order, sort. For the top hundred of four thousand, a heap. When every search must be linear, median of medians picks a pivot that always rules out a fixed share. Python 3.14's statistics.median sorts first, then reads the middle.

how it compares

Quickselect beside sorting first and then reading place kk, which costs no comparison.

wayworks onaverage on 8most on 81,000 shuffled, average of 2001,000 in order, place 1
quickselectone side of each split12.54283,033499,500
quick sortboth sides of each split16.922811,055499,500
merge sortevery half15.73178,7195,052
heap sortthe whole heap25.812916,85517,583
Each way's comparisons, by the site's own module. The average of 200 random shuffles sits near the exact average over every order, not on it: quickselect's 3,033 against 2,953.
10210410610810101012101410110210310410510610710110210310410510610710810910101011101210131014101102103104105106107
  • quickselect, shuffled, on average
  • quick sort, shuffled, on average, by its own page
  • merge sort at most, by its own page
  • quickselect, a row in order asked for its smallest
On average quickselect climbs one mark for each mark across, the sorts a little more. At a million numbers, about 3 million comparisons against quick sort's 25 million. A row in order asked for its smallest climbs two.

race them on one row of your own