Quickselect
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 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 , it is the answer. If not, only one side can hold place . 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.
step 2 of 35
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.
step 8 of 35
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
step 12 of 35
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.
step 13 of 35
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.
step 21 of 35
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.
step 22 of 35
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.
step 28 of 35
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.
step 34 of 35
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- the part to search is the whole rowPython lines 10 and 11
- a part of one number holds the number wantedPython lines 12 and 28
- take the part's last number as the pivotPython line 13
- look at each other number in the part, from the leftPython line 15
- if it is smaller than the pivot, swap it onto the small sidePython lines 14, 16, 17 and 18
- swap the pivot in just after the small sidePython line 21
- if the pivot stands at the place wanted, it is the number wantedPython lines 22 and 23
- 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
, 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
| comparisons | time | |
|---|---|---|
| 1,000 | 499,500 | about 500 microseconds |
| 100,000 | 4,999,950,000 | about 5 seconds |
| 10,000,000 | 49,999,995,000,000 | about 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.
| best1 to n in order, asking for the biggest | averageshuffled, averaged over every order of different numbers and every place | worst1 to n in order, asking for the smallest | |
|---|---|---|---|
| comparisons | , one split | , under ; 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.54 | , a split of each length |
| how the comparisons grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
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.
| place asked for | average comparisons |
|---|---|
| 1 | 10.56 |
| 2 | 12.25 |
| 3 | 13.39 |
| 4 | 13.95 |
| 5 | 13.95 |
| 6 | 13.39 |
| 7 | 12.25 |
| 8 | 10.56 |
where the formula comes from
Each count above, worked out in small steps. Every step names the line it uses.
the move: price one split
the line:why it is allowed: Each number but the pivot is compared with the pivot, once.
the move: see a row in order asked for its smallest
the line: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.
guess it, thenthe move: add up the splits
the line:why it is allowed: is the comparisons asking 1 to in order for the smallest. By line 2 the parts hold , then , down to 2. By line 1 each costs one less.
guess it, thenthe move: add the counting numbers
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
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 .
guess it, thenthe move: tidy
the line:why it is allowed: is . For 5 numbers, 5 times 4 over 2 is 10, as in the picture.
guess it, thenthe move: no row or place costs more
the line: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 . 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, numbers make 1, plus 2, and on up to pairs, line 3's sum backwards. So no search makes more than comparisons. Here every pair meets: the bigger is a pivot first, with the smaller still in its part.
guess it, thenthe move: a ceiling
the line:why it is allowed: In line 5, is less than . For 5, 10 is under 12.5.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, stays under a half of , and a half is the fixed multiple.
guess it, thenthe move: a floor
the line:why it is allowed: In line 5, is at least a half of once is 2 or more. For 5, 10 is at least 6.25.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 9, never drops below a quarter of , and a quarter is the fixed multiple.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 8 and 10 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: price the first split
the line: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 .
the move: see a search end at once
the line: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 , the biggest. Nothing is bigger, so it lands at place , the place wanted, and the search ends.
guess it, thenthe move: count it
the line:why it is allowed: is the fewest comparisons any row and place of numbers can cost. By line 1 no search costs fewer, and by line 2 this one costs just that. For 5 numbers, 4.
guess it, thenthe move: a ceiling
the line:why it is allowed: In line 3, is less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 4.
guess it, thenthe move: a floor
the line:why it is allowed: From 2 numbers on, 1 is at most half of , so is at least the other half.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 5 and 7 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: name the numbers
the line:order place 1 place 2 place 3 1, 2, 3 3 3 2 2, 1, 3 3 3 2 3, 1, 2 2 2 2 1, 3, 2 2 2 2 2, 3, 1 2 3 3 3, 2, 1 2 3 3 in all 14 16 14 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 different numbers act like 1 to , and place wants itself.
the move: draw the stretch
the line: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, the smaller and the bigger.
guess it, thenthe move: the stretch stays together
the line:why it is allowed: A pivot below the stretch or above it sends all of the stretch to one side. Place is in the stretch, so that side is the one kept.
guess it, thenthe move: an end comes first
the line: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.
guess it, thenthe move: a number between parts them
the line: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 and the search ends.
guess it, thenthe move: the rest rule them out
the line: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. 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 , found, and is neither of them, so neither is compared with the other.
guess it, thenthe move: see each come first equally often
the line: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. 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 numbers comes first equally often, 1 in . By lines 4 to 6, two of them make the pair meet.
guess it, thenthe move: add each pair's share
the line:order first pivot from 1 to 3 1 and 2 meet 1 and 3 meet 2 and 3 meet comparisons 1, 2, 3 3 1 1 1 3 2, 1, 3 3 1 1 1 3 3, 1, 2 2 1 0 1 2 1, 3, 2 2 1 0 1 2 2, 3, 1 1 1 1 0 2 3, 2, 1 1 1 1 0 2 in all 6 4 4 14 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.
guess it, thenthe move: count the ways to a stretch
the line: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 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: ways. 1 the pair's smaller and the place: the bigger is any of 2 up to less 1, less 2 ways. The place 1 and the pair's bigger: less 2 more. In all, pair and place choices; for of 4, 4 + 2 + 2 = 8, the picture's three groups. With 1, 2, 3, 3 + 1 + 1 is 5.
guess it, thenthe move: slide the stretch
the line:stretch 1 2 3 4 5 1 to 3 1 2 3 2 to 4 2 3 4 3 to 5 3 4 5 Stretches of 3 among 5 numbers, a row each. They start at 1, 2 and 3, and is 5 less 3, plus 1, so 3 stretches. why it is allowed: A stretch of numbers starts at 1, 2, and on up to , and sliding it changes nothing in line 9. With 1, 2, 3, stretches of 2 start at 1 and 2, of 3 at 1.
guess it, thenthe move: average pair by pair
the line:stretches pair and place choices share product 2 2 2 2 over 2 4 3 1 5 2 over 3 10 thirds in all 22 thirds The sum for 3 numbers, a row for each . 22 thirds over 3 places is 22 ninths, line 1's 44 over 18. why it is allowed: 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 pairs and places for each , each meeting in 2 of every shuffles by line 7, and dividing by averages the places.
guess it, thenthe move: share out 2 over s
the line:why it is allowed: times 2 over is over , less 8 over , which is 6 less 8 over . For of 2, 2 times 2 over 2 is 2, and 6 less 4 is 2.
guess it, thenthe move: multiply out, keeping n + 1 together
the line:times The four products. For 3 numbers and of 2, 24, less 16, less 12, plus 8 is 4, as 2 times 2 is. why it is allowed: Read as , less , and multiply each by 6 less 8 over , as in the grid. times 8 over is 8.
guess it, thenthe move: add up each part
the line:why it is allowed: takes values, 2 up to . A part that does not change with is added times. A multiplier on every term, such as or 6, comes out in front of the sum. For 3, is 2 and 3, and 6 times 4 added twice is 48.
guess it, thenthe move: add 2 up to n
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: The fold adds the whole numbers from 1 up to with two staircases, times , halved. The sum here leaves out the 1. For 3, 2 + 3 is 5, which is 6 less 1.
guess it, thenthe move: name the harmonic sum
the line:where does this come from?
question 4 of the page expected costHow does grow? the move: name the sum
the line:why it is allowed: Let be the harmonic sum to 1 over , for from 2.
the move: group in blocks
the line: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 from 0. Block starts at 1 over 2 to the power : 1, 1 over 2, 1 over 4, 1 over 8. It stops just before the next start, so it has 2 to the power terms: 1 over 4 to 1 over 7 are 4. The last block may be cut short at 1 over .
the move: each block at most 1
the line:why it is allowed: Each term of block is at most its first, 1 over 2 to the power , as a bigger number underneath makes a smaller fraction. So its 2 to the power terms, or fewer, add to at most 1. is at most 1 per block: 4 for 12.
the move: count the blocks
the line:where does this come from?
question 2 of the page halving and logarithmsHalve , rounding down each time. How many halvings reach 1? the move: name the log rounded down
the line: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 is the number halved, from 2 up; for 11, is 3.
the move: rounding down never adds
the line:why it is allowed: For 11, 3 is at most 3.46.
the move: rounding down takes off less than 1
the line:why it is allowed: For 11, 4 is above 3.46.
the move: raise 2 to each side of line 2
the line:why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.
the move: 2 to the log of n is n
the line:why it is allowed: By what a log is. For 11, 8 is at most 11.
the move: raise 2 to each side of line 3
the line:why it is allowed: As in line 4. For 11, about 11 is below 16.
the move: 2 to the log of n is n
the line:why it is allowed: As in line 5. For 11, 11 is below 16.
the move: halve both sides of line 5
the line:why it is allowed: For 11, 4 is at most 5.5, which is not whole.
the move: write the half as a power
the line:why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.
the move: round the half down
the line:why it is allowed: 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 is at least 1 for from 2 up.
the move: halve both sides of line 7
the line:why it is allowed: For 11, 5.5 is below 8.
the move: write the half as a power
the line:why it is allowed: As in line 9. Half of 16 is 8.
the move: round the half down
the line:why it is allowed: Rounding down never adds. For 11, 5 is below 8.
the move: take the log of line 10
the line:why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, the log of 4 is 2, at most about 2.32.
the move: take the log of line 13
the line:why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, about 2.32 is below 3.
the move: round the log down
the line:the number at least below its log rounded down 11 8 16 3 5 4 8 2 2 2 4 1 1 1 2 0 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 and below , so it rounds down to one less. For 11, about 2.32 rounds down to 2.
the move: use line 18 again and again
the line: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 . For 11, 3, 2, 1, 0.
the move: a log rounded down to 0 belongs to 1
the line: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.
why it is allowed: is read the log of rounded down. By lines 5 and 7 of the page halving and logarithms, 2 to that power is at most , and the next power of 2 is above . So blocks start at 1 over 2 to the powers 0 to . For 12, 3.58 rounds down to 3: the 4 blocks of line 2.
the move: drop the rounding
the line:why it is allowed: Rounding down never adds, so putting for can never lower the right side. For 12, 4 becomes about 4.58.
the move: a fact about n
the line:why it is allowed: is at least 2, the log of 2 is 1, and a bigger number has a bigger log.
the move: put the log in place of the 1
the line: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.
the move: add the logs
the line:why it is allowed: Two lots of .
the move: a ceiling
the line:why it is allowed: By line 8, is at most 2 times for every from 2. , read is in big O of , says a fixed multiple of is a ceiling of : here 2.
the move: blocks after the first term
the line: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 .
the move: drop the leftovers
the line:why it is allowed: Leftover terms are above zero, so leaving them out makes the total no bigger.
the move: whole blocks at least one half
the line:why it is allowed: Number the whole blocks by from 1. Block runs from just after 1 over half of 2 to the power to 1 over 2 to the power . 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, is at least 1 plus one half per whole block: 2.5.
the move: count the whole blocks
the line:where does this come from?
question 2 of the page halving and logarithmsHalve , rounding down each time. How many halvings reach 1? the move: name the log rounded down
the line: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 is the number halved, from 2 up; for 11, is 3.
the move: rounding down never adds
the line:why it is allowed: For 11, 3 is at most 3.46.
the move: rounding down takes off less than 1
the line:why it is allowed: For 11, 4 is above 3.46.
the move: raise 2 to each side of line 2
the line:why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.
the move: 2 to the log of n is n
the line:why it is allowed: By what a log is. For 11, 8 is at most 11.
the move: raise 2 to each side of line 3
the line:why it is allowed: As in line 4. For 11, about 11 is below 16.
the move: 2 to the log of n is n
the line:why it is allowed: As in line 5. For 11, 11 is below 16.
the move: halve both sides of line 5
the line:why it is allowed: For 11, 4 is at most 5.5, which is not whole.
the move: write the half as a power
the line:why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.
the move: round the half down
the line:why it is allowed: 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 is at least 1 for from 2 up.
the move: halve both sides of line 7
the line:why it is allowed: For 11, 5.5 is below 8.
the move: write the half as a power
the line:why it is allowed: As in line 9. Half of 16 is 8.
the move: round the half down
the line:why it is allowed: Rounding down never adds. For 11, 5 is below 8.
the move: take the log of line 10
the line:why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, the log of 4 is 2, at most about 2.32.
the move: take the log of line 13
the line:why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, about 2.32 is below 3.
the move: round the log down
the line:the number at least below its log rounded down 11 8 16 3 5 4 8 2 2 2 4 1 1 1 2 0 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 and below , so it rounds down to one less. For 11, about 2.32 rounds down to 2.
the move: use line 18 again and again
the line: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 . For 11, 3, 2, 1, 0.
the move: a log rounded down to 0 belongs to 1
the line: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.
why it is allowed: As in line 4, whole blocks end at 1 over 2 to the powers 1 to , that many blocks. For 12, 3.
the move: rounding takes off less than 1
the line:why it is allowed: Rounding down takes off less than 1, so putting less 1 for can only lower the right side. For 12, 2.5 becomes about 2.29.
the move: halve each part
the line:why it is allowed: Half of ( less 1) is half of , less one half.
the move: change the order
the line:why it is allowed: Adding and taking away go in any order.
the move: 1 less one half
the line:why it is allowed: 1 less one half is one half.
the move: drop the one half
the line:why it is allowed: Taking away one half makes the right side smaller. For 12, about 1.79.
the move: a floor
the line:- the ceiling,
- the harmonic sum
- the floor,
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, is at least one half times for every from 2. , read is in big omega of , says a fixed multiple of , above zero, is a floor of .
the move: ceiling and floor together
the line:why it is allowed: , read is in big theta of , says both: by lines 9 and 19, for every from 2, lies between one half and 2 times . It grows like .
why it is allowed: The sum here is , the harmonic sum, without its first 1. The fold shows how grows. For 3, a half and a third make 5 sixths, and is 1 + a half + a third, 11 sixths.
guess it, thenthe move: open the brackets
the line:why it is allowed: Open line 16's four parts, a row each. is less 1. Taking 1 from , times is plus 8 lots of , which is . 6 times half of is 3 lots of and 3 of , and minus 6 times minus 1 is plus 6.
guess it, thenthe move: gather
the line:part opened out number in all 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.
guess it, thenthe move: divide by n
the line:why it is allowed: Divide each part by . 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.
guess it, thenthe move: a ceiling from line 12
the line:why it is allowed: In line 12, each stretch's share, 6 less 8 over , is less than 6.
guess it, thenthe move: add the counting numbers
the line:why it is allowed: As runs from 2 to , runs from down to 1. By the fold at line 15, those add up to times , halved. The 6 comes out in front, as in line 14.
guess it, thenthe move: tidy
the line:why it is allowed: 6 over , times , halved, is 3. For 3 numbers that is 6, and the average is 22 ninths, about 2.44.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: is less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 23.
guess it, thenthe move: a floor from the first split
the line:why it is allowed: Every search splits all numbers first, by line 1 of the second ladder, so their average does too.
guess it, thenthe move: a simpler floor
the line:why it is allowed: In line 25, from 2 numbers on, 1 is at most half of , so is at least the other half.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 26.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 24 and 27 bound by the same growth, .
guess it, then
try it on small inputs: over the 6 orders of 1, 2, 3 and each of the 3 places, 18 searches, the average 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.
| step | the row | what happens | comparisons | swaps |
|---|---|---|---|---|
| 1 | 27, 35, 48, 14, 62 | There 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, 62 | 0 | 0 |
| 2 | 27, 35, 48, 14, 62 | Search 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, 62 | 0 | 0 |
| 3 | 27, 35, 48, 14, 62 | 27 is smaller than the pivot 62, and it already stands at the end of the small side.27, 35, 48, 14, 62 | 1 | 0 |
| 4 | 27, 35, 48, 14, 62 | 35 is smaller than the pivot 62, and it already stands at the end of the small side.27, 35, 48, 14, 62 | 2 | 0 |
| 5 | 27, 35, 48, 14, 62 | 48 is smaller than the pivot 62, and it already stands at the end of the small side.27, 35, 48, 14, 62 | 3 | 0 |
| 6 | 27, 35, 48, 14, 62 | 14 is smaller than the pivot 62, and it already stands at the end of the small side.27, 35, 48, 14, 62 | 4 | 0 |
| 7 | 27, 35, 48, 14, 62 | The 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, 62 | 4 | 0 |
| 8 | 27, 35, 48, 14, 62 | Place 3 lies to the left of place 5, so rule out the pivot 62 and every number to its right.27, 35, 48, 14, 62 | 4 | 0 |
| 9 | 27, 35, 48, 14, 62 | Search 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, 62 | 4 | 0 |
| 10 | 27, 35, 48, 14, 62 | 27 is not smaller than the pivot 14, so it stays on the big side.27, 35, 48, 14, 62 | 5 | 0 |
| 11 | 27, 35, 48, 14, 62 | 35 is not smaller than the pivot 14, so it stays on the big side.27, 35, 48, 14, 62 | 6 | 0 |
| 12 | 27, 35, 48, 14, 62 | 48 is not smaller than the pivot 14, so it stays on the big side.27, 35, 48, 14, 62 | 7 | 0 |
| 13 | 14, 35, 48, 27, 62 | Swap 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, 62 | 7 | 1 |
| 14 | 14, 35, 48, 27, 62 | Place 3 lies to the right of place 1, so rule out the pivot 14 and every number to its left.14, 35, 48, 27, 62 | 7 | 1 |
| 15 | 14, 35, 48, 27, 62 | Search 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, 62 | 7 | 1 |
| 16 | 14, 35, 48, 27, 62 | 35 is not smaller than the pivot 27, so it stays on the big side.14, 35, 48, 27, 62 | 8 | 1 |
| 17 | 14, 35, 48, 27, 62 | 48 is not smaller than the pivot 27, so it stays on the big side.14, 35, 48, 27, 62 | 9 | 1 |
| 18 | 14, 27, 48, 35, 62 | Swap 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, 62 | 9 | 2 |
| 19 | 14, 27, 48, 35, 62 | Place 3 lies to the right of place 2, so rule out the pivot 27 and every number to its left.14, 27, 48, 35, 62 | 9 | 2 |
| 20 | 14, 27, 48, 35, 62 | Search 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, 62 | 9 | 2 |
| 21 | 14, 27, 48, 35, 62 | 48 is not smaller than the pivot 35, so it stays on the big side.14, 27, 48, 35, 62 | 10 | 2 |
| 22 | 14, 27, 35, 48, 62 | Swap 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, 62 | 10 | 3 |
| 23 | 14, 27, 35, 48, 62 | The pivot 35 stands at place 3, the place wanted, so it is the number wanted.14, 27, 35, 48, 62 | 10 | 3 |
| 24 | 14, 27, 35, 48, 62 | Found, after 10 comparisons and 3 swaps.14, 27, 35, 48, 62 | 10 | 3 |
In all, 10 comparisons. The formula from section 4, , gives at : 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 , 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 , which costs no comparison.
| way | works on | average on 8 | most on 8 | 1,000 shuffled, average of 200 | 1,000 in order, place 1 |
|---|---|---|---|---|---|
| quickselect | one side of each split | 12.54 | 28 | 3,033 | 499,500 |
| quick sort | both sides of each split | 16.92 | 28 | 11,055 | 499,500 |
| merge sort | every half | 15.73 | 17 | 8,719 | 5,052 |
| heap sort | the whole heap | 25.81 | 29 | 16,855 | 17,583 |
- 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