Randomised quick sort
how it works
The idea in a few sentences and two pictures, then one row sorted step by step.
Randomised quick sort is quick sort with one change: the pivot is picked at random from the part, every place as likely. The pivot is swapped to the end of the part, out of the way. Then the part is split as quick sort splits it: each smaller number swaps onto the small side, and the pivot swaps in just after it, placed for good. The parts still to sort wait in a list, each kept as its first and last place. Plain quick sort always takes the last number, so a row in order is its dearest: 28 comparisons on 10, 20, up to 80. With random picks, that row cost 15 here, as section 3 draws. The picks come from the site's own generator, the same picks each time you watch the same row.
step 2 of 43
Sort the part from place 1 to place 8. Pick one of its places at random: place 6, so its number, 23, is the pivot.
what it remembers to know where it is
- pivot
- 23
- place picked
- 6
- part starts at place
- 1
- part ends at place
- 8
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
step 3 of 43
Swap the pivot 23 to the end of the part, out of the way, and 49 goes where 23 was.
what it remembers to know where it is
- pivot
- 23
- place picked
- 6
- part starts at place
- 1
- part ends at place
- 8
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
step 6 of 43
Swap 7 onto the small side, and 42 goes where 7 was.
what it remembers to know where it is
- pivot
- 23
- place picked
- not yet
- part starts at place
- 1
- part ends at place
- 8
- looking at place
- 2
Where it says not yet, nothing is held there at that moment.
step 14 of 43
Swap the pivot 23 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.
what it remembers to know where it is
- pivot
- 23
- place picked
- not yet
- part starts at place
- 1
- part ends at place
- 8
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
step 16 of 43
Sort the part from place 1 to place 3. Pick one of its places at random: place 3, so its number, 12, is the pivot.
what it remembers to know where it is
- pivot
- 12
- place picked
- 3
- part starts at place
- 1
- part ends at place
- 3
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
step 43 of 43
In order, after 15 comparisons and 9 swaps.
what it remembers to know where it is
- pivot
- not yet
- place picked
- not yet
- part starts at place
- not yet
- part ends at place
- not yet
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- sort the whole row as one partPython line 14
- a part of one number is in placePython lines 17 and 18
- pick a place in the part at random, and its number is the pivotPython line 20
- swap the pivot to the end of the part, out of the wayPython lines 21, 22 and 23
- look at each other number in the part, from the leftPython line 25
- if it is smaller than the pivot, swap it onto the small sidePython lines 24, 26, 27 and 28
- swap the pivot in just after the small side, where it staysPython lines 30 and 31
- sort the part on its left, then the part on its rightPython lines 15, 16, 32 and 33
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
import random
def randomised_quick_sort(numbers, pick=random.randint):
"""Put a list of numbers in order, smallest first, in the list itself.
Each part of the list gets a pivot picked at random: pick(low, high)
gives a place from low to high, each as likely. The pivot is swapped to
the part's end, out of the way, and the part is split round it as quick
sort splits it: every smaller number is swapped onto a small side at the
left, and the pivot is swapped in just after it, where it stays. Then the
part on each side is sorted the same way, the left one first.
"""
parts = [(0, len(numbers) - 1)] # sort the whole list as one part
while parts:
low, high = parts.pop()
if low >= high: # a part of one number, or none, is in place
continue
chosen = pick(low, high) # a place in the part, at random
# the pivot goes to the end of the part, out of the way
numbers[chosen], numbers[high] = numbers[high], numbers[chosen]
pivot = numbers[high]
small = low # where the small side ends
for place in range(low, high): # each other number, from the left
if numbers[place] < pivot: # smaller: onto the small side
numbers[small], numbers[place] = numbers[place], numbers[small]
small += 1
# the pivot goes just after the small side, and stays there
numbers[small], numbers[high] = numbers[high], numbers[small]
parts.append((small + 1, high)) # the part on its right waits,
parts.append((low, small - 1)) # the part on its left goes first
return numbers
how it scales
How the comparisons grow, from ten numbers to ten million.
Each step across or up is ten times the one before, a log-log plot. The line climbs only a little more than one step up for each step across. It is the average over the picks, the same for a row in order as for a shuffle. Each point is 20 shuffles, each sorted once, which averages the same as one row sorted again and again.
comparisons, ten times more at each mark up
, how many numbers are in the row, ten times more at each mark to the right
- every row of different numbers, averaged over the pickssolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, about 12 times the work
| comparisons | time | |
|---|---|---|
| 1,000 | 10,986 | about 11 microseconds |
| 100,000 | 2,018,053 | about 2 milliseconds |
| 10,000,000 | 293,906,261 | about 294 milliseconds |
The comparisons are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
import random
def randomised_quick_sort(numbers, pick=random.randint):
"""Put a list of numbers in order, smallest first, in the list itself.
Each part of the list gets a pivot picked at random: pick(low, high)
gives a place from low to high, each as likely. The pivot is swapped to
the part's end, out of the way, and the part is split round it as quick
sort splits it: every smaller number is swapped onto a small side at the
left, and the pivot is swapped in just after it, where it stays. Then the
part on each side is sorted the same way, the left one first.
"""
parts = [(0, len(numbers) - 1)] # sort the whole list as one part
while parts:
low, high = parts.pop()
if low >= high: # a part of one number, or none, is in place
continue
chosen = pick(low, high) # a place in the part, at random
# the pivot goes to the end of the part, out of the way
numbers[chosen], numbers[high] = numbers[high], numbers[chosen]
pivot = numbers[high]
small = low # where the small side ends
for place in range(low, high): # each other number, from the left
if numbers[place] < pivot: # smaller: onto the small side
numbers[small], numbers[place] = numbers[place], numbers[small]
small += 1
# the pivot goes just after the small side, and stays there
numbers[small], numbers[high] = numbers[high], numbers[small]
parts.append((small + 1, high)) # the part on its right waits,
parts.append((low, small - 1)) # the part on its left goes first
return numbers
# Count randomised quick sort's comparisons yourself, as the plot on this page
# does. Run this file with Python 3.12 or later. For each size n it prints the
# average comparisons over 20 runs on a row in order and on 20 shuffles. Your
# picks are random, so your numbers will differ a little from the page's; the
# counts do not depend on the computer, only the time taken does.
class Counted:
"""A number that counts every comparison made with it."""
comparisons = 0
def __init__(self, value):
self.value = value
def __lt__(self, other):
Counted.comparisons += 1
return self.value < other.value
def count(row, pick=random.randint):
"""How many comparisons randomised quick sort makes on this row."""
Counted.comparisons = 0
randomised_quick_sort([Counted(x) for x in row], pick)
return Counted.comparisons
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>7} {'in order':>10} {'shuffled':>10}")
for n in [10, 100, 1000, 10000]:
in_order = sum(count(list(range(1, n + 1))) for _ in range(20)) / 20
shuffles = []
for _ in range(20):
row = list(range(1, n + 1))
random.shuffle(row)
shuffles.append(count(row))
print(f"{n:>7} {in_order:>10.1f} {sum(shuffles) / 20:>10.1f}")
extra memory, the places the sort holds beyond the row itself, ten times more at each mark up
, how many numbers are in the row, ten times more at each mark to the right
- every row of different numbers, averaged over the pickspoints only, each measured by a real run, since no single formula for the extra memory of this row is worked out here
best, worst and average
The picks decide the cost, not the order of the row, so the grid has one column, the average over the picks, on any row of different numbers. For 1, 2, 3 it is 8 over 3, as section 4 counts. The luckiest picks cost what quick sort's cheapest row costs, and the unluckiest what its dearest costs: on 8 numbers, 13 and 28. The quick sort page works both out. The second picture shows the 28: its row is dear because of its picks, not its order.
A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| averageevery row of different numbers, averaged over the picks | |
|---|---|
| comparisons | |
| how the comparisons grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
extra memory: a list of the parts waiting to be sorted, each kept as its first and last place. On average far shorter than the row, about 66 places for a million numbers. Unlucky picks can make it grow with the row
Extra memory is the room it needs on top of the input itself, while it runs.
where the formula comes from
Each count above, worked out in small steps. Every step names the line it uses.
the move: name the numbers
the line:why it is allowed: The average here is over the picks, on one row. The splits care only which number is smaller than which, so call the smallest 1, the next 2, and on up. So 26, 12, 40 become 2, 1, 3.
the move: watch two numbers
the line:first pivot 2 5 so 7 left part left part they wait in one part 3 left part right part they never meet 2 the pivot compared with 2 they meet 5 compared with 5 the pivot they meet Watching 2 and 5 in 1 to 8. A pivot outside 2 to 5 keeps them together, as in line 2; 3 or 4 parts them, line 3; 2 or 5 compares them, line 4. why it is allowed: Take two numbers, the smaller and the bigger. A pivot below or above sends every number from to the same way. The table watches 2 and 5 in 1 to 8.
guess it, thenthe move: a number between parts them
the line:why it is allowed: That pivot sends left and right, into different parts. Every comparison is with a pivot, and neither of them was one before, or is one now, so they never meet.
guess it, thenthe move: an end meets the other
the line:why it is allowed: Every comparison is with a pivot, and neither was one before, so they have not met yet. By line 2 the other is still in its part, so the split compares them. The pivot is then placed, outside both parts, so they never meet again.
guess it, thenthe move: see each picked first equally often
the line:first pick then 1, 3 meet comparisons 1 split 2, 3 yes 3 2 two lone numbers no 2 3 split 1, 2 yes 3 average 2 in 3 8 over 3 The row 1, 2, 3 and each first pick, each as likely. Whatever comes after costs the same either way. why it is allowed: Every pick is as likely to land on one place of its part as on any other. While the numbers from to share a part, a pick landing on one of them is as likely to land on any of the others. So each of the numbers is as likely to be picked first. By lines 3 and 4, the pair meets when it is or . In the table, 1 and 3 meet with a chance of 2 in 3.
guess it, thenthe move: add the pairs' chances
the line:pair apart numbers from one to the other chance of meeting 1, 2 1 2 2 in 2 2, 3 1 2 2 in 2 1, 3 2 3 2 in 3 in all 8 over 3 The row 1, 2, 3 pair by pair, each chance from line 5. The chances add up to the average, 8 over 3. why it is allowed: A pair adds 1 comparison to a run when it meets, by line 4, and 0 when it does not. So on average it adds its chance of meeting. Averages add, as the expected-cost page shows in its pairs question, line 2. For 1, 2, 3, the table adds 1, 1 and 2 in 3: 8 over 3, the average at line 5.
guess it, thenthe move: group the pairs by how far apart
the line:why it is allowed: is the comparisons averaged over the picks. Two numbers stand apart when the bigger is the smaller plus , with from 1 to , so each pair is in one group. Each of 1, 2, and on up to has a partner above it, so pairs stand apart. For 4 numbers, 1 apart are 1 and 2, 2 and 3, 3 and 4; 2 apart, 1 and 3, 2 and 4; 3 apart, 1 and 4. From to there are numbers, so by line 5 each meets with a chance of 2 in . Line 6 adds them. For 4 numbers: 3 pairs at 2 in 2, 2 at 2 in 3, 1 at 2 in 4. That is 3, plus 4 thirds, plus a half, 29 over 6.
guess it, thenthe move: write each term with its bottom
the line:why it is allowed: Each term's bottom is , from 2 to . Its count of pairs, , is take away that bottom; for the first term, is .
guess it, thenthe move: multiply out each term
the line:why it is allowed: The second term, , is , since 3 times 2 over 3 is 2. Every term takes away 2 the same way.
guess it, thenthe move: take out the common part, add up the 2s
the line:why it is allowed: The terms of line 9 each take away 2, and each hold over their bottom.
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 bracket of line 10 is without its first 1. The fold shows how grows.
guess it, thenthe move: open the first bracket
the line:why it is allowed: Taking 1 away inside the bracket takes away .
guess it, thenthe move: gather
the line:why it is allowed: and add up to , the 2 and the take-away 2 cancelling. For 3 numbers, is 1, plus a half, plus a third, which is 11 sixths. So 2 times 4 times 11 sixths, less 12, is 8 over 3, the tables' average. Nothing here hangs on the row's order, so every row of different numbers averages the same.
guess it, thenthe move: how big the harmonic sum gets
the line:why it is allowed: The fold at line 11 shows this, in its line 5.
guess it, thenthe move: a ceiling
the line:why it is allowed: Put line 14 into line 13. is multiplied by , which is positive, so a bigger value in its place gives a ceiling. At 1 number is 0, so this holds there too.
guess it, thenthe move: open the bracket
the line:why it is allowed: Multiply by each of and 1.
guess it, thenthe move: gather
the line:why it is allowed: less leaves .
guess it, thenthe move: drop what is not positive
the line:why it is allowed: From 1 number on, is at most 0.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: is at most , and is not negative.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 19, stays under 4 times .
guess it, thenthe move: how small the harmonic sum gets
the line:why it is allowed: The fold at line 11 shows this, in its line 17.
guess it, thenthe move: a floor
the line:why it is allowed: Put line 21 into line 13. is multiplied by , which is positive, so a smaller value in its place gives a floor. At 1 number is 0, and the right side is less.
guess it, thenthe move: take the 2 into the bracket
the line:why it is allowed: 2 times a half is 1, and 2 times is .
guess it, thenthe move: a smaller floor
the line:why it is allowed: is more than , and is positive.
guess it, thenthe move: open the bracket
the line:why it is allowed: times 1 is , and less is .
guess it, thenthe move: what 16 numbers allow
the line:why it is allowed: From 16 numbers on, is at least 4, so of it is at least 3.
guess it, thenthe move: take away more
the line:why it is allowed: Put line 26 into line 25. Taking away more leaves less, so the floor still holds.
guess it, thenthe move: tidy
the line:why it is allowed: One whole , less three quarters of it, leaves a quarter of it.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 28, from 16 numbers on, stays above a quarter of .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 20 and 29 bound by the same growth, .
guess it, then
try it on small rows: over every order of 16 numbers, the average is about 50.94
the move: no number is smaller
the line:Five equal numbers. Each split places its pivot and leaves the rest in one part. 4 + 3 + 2 + 1 = 10 comparisons. why it is allowed: A split moves only numbers smaller than the pivot. Whatever place is picked, each split leaves all the others in one part, as the picture shows.
the move: price one split
the line:why it is allowed: Each number but the pivot is compared with the pivot, once.
guess it, thenthe move: add up the splits
the line:why it is allowed: is the comparisons on a row of equal numbers. By line 1 the parts hold , then , and on down to 2 numbers. By line 2 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: a ceiling
the line:why it is allowed: In line 5, is less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6, stays under half of .
guess it, thenthe move: a floor
the line:why it is allowed: In line 5, is at least half of once is 2 or more.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8, from 2 numbers on, never drops below a quarter of .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 7 and 9 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: the unluckiest picks
the line:why it is allowed: Then each split leaves one part of all the rest, as with equal numbers. So lines 2 to 5 of the ladder before give the count, with this sentence in place of its line 1. The second picture of section 3 is such a run.
the move: the chance at one split
the line:why it is allowed: Each of the places is as likely, and two of them hold the biggest and the smallest.
guess it, thenthe move: every split unlucky
the line:pick runs still unlucky unlucky this time runs left first 24 2 in 4 12 second 12 2 in 3 8 third 8 2 in 2 8 24 runs on 4 different numbers, as the chances share them out, followed pick by pick. Half start unlucky, 2 in 3 of those stay unlucky, and all of those end unlucky. 8 of 24 is a third. why it is allowed: is the chance that every pick is the biggest or smallest left. Each pick is fair on its own part, whatever came before. The first pick is unlucky in 2 of every runs. Of those, the next is unlucky in 2 of every , and on down to the part of 2. A share of a share multiplies, as the table follows 24 runs. For 4 numbers, 2 in 4, then 2 in 3 of those, then 2 in 2, is 8 in 24.
guess it, thenthe move: gather tops and bottoms
the line:why it is allowed: There are twos on top, and times and on down to 2 underneath, which is . For 4 numbers, 8 over 24, a third; for 8 numbers, 128 over 40,320, exactly 1 in 315.
guess it, then
try it with a small : at , line 3 gives , about 0.33
count it yourself
Count every comparison on five equal numbers, then check the total against the formula for equal numbers.
| step | the row | what happens | comparisons | swaps |
|---|---|---|---|---|
| 1 | 9, 9, 9, 9, 9 | There are 5 numbers in a row. Sort the whole row as one part.9, 9, 9, 9, 9 | 0 | 0 |
| 2 | 9, 9, 9, 9, 9 | Sort the part from place 1 to place 5. Pick one of its places at random: place 3, so its number, 9, is the pivot.9, 9, 9, 9, 9 | 0 | 0 |
| 3 | 9, 9, 9, 9, 9 | Swap the pivot 9 to the end of the part, out of the way, and 9 goes where 9 was.9, 9, 9, 9, 9 | 0 | 1 |
| 4 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 1 | 1 |
| 5 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 2 | 1 |
| 6 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 3 | 1 |
| 7 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 4 | 1 |
| 8 | 9, 9, 9, 9, 9 | Swap the pivot 9 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.9, 9, 9, 9, 9 | 4 | 2 |
| 9 | 9, 9, 9, 9, 9 | Nothing lies to its left and 4 to its right: sort each side the same way, the left one first.9, 9, 9, 9, 9 | 4 | 2 |
| 10 | 9, 9, 9, 9, 9 | Sort the part from place 2 to place 5. Pick one of its places at random: place 4, so its number, 9, is the pivot.9, 9, 9, 9, 9 | 4 | 2 |
| 11 | 9, 9, 9, 9, 9 | Swap the pivot 9 to the end of the part, out of the way, and 9 goes where 9 was.9, 9, 9, 9, 9 | 4 | 3 |
| 12 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 5 | 3 |
| 13 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 6 | 3 |
| 14 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 7 | 3 |
| 15 | 9, 9, 9, 9, 9 | Swap the pivot 9 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.9, 9, 9, 9, 9 | 7 | 4 |
| 16 | 9, 9, 9, 9, 9 | Nothing lies to its left and 3 to its right: sort each side the same way, the left one first.9, 9, 9, 9, 9 | 7 | 4 |
| 17 | 9, 9, 9, 9, 9 | Sort the part from place 3 to place 5. Pick one of its places at random: place 4, so its number, 9, is the pivot.9, 9, 9, 9, 9 | 7 | 4 |
| 18 | 9, 9, 9, 9, 9 | Swap the pivot 9 to the end of the part, out of the way, and 9 goes where 9 was.9, 9, 9, 9, 9 | 7 | 5 |
| 19 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 8 | 5 |
| 20 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 9 | 5 |
| 21 | 9, 9, 9, 9, 9 | Swap the pivot 9 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.9, 9, 9, 9, 9 | 9 | 6 |
| 22 | 9, 9, 9, 9, 9 | Nothing lies to its left and 2 to its right: sort each side the same way, the left one first.9, 9, 9, 9, 9 | 9 | 6 |
| 23 | 9, 9, 9, 9, 9 | Sort the part from place 4 to place 5. Pick one of its places at random: place 4, so its number, 9, is the pivot.9, 9, 9, 9, 9 | 9 | 6 |
| 24 | 9, 9, 9, 9, 9 | Swap the pivot 9 to the end of the part, out of the way, and 9 goes where 9 was.9, 9, 9, 9, 9 | 9 | 7 |
| 25 | 9, 9, 9, 9, 9 | 9 is not smaller than the pivot 9, so it stays on the big side.9, 9, 9, 9, 9 | 10 | 7 |
| 26 | 9, 9, 9, 9, 9 | Swap the pivot 9 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.9, 9, 9, 9, 9 | 10 | 8 |
| 27 | 9, 9, 9, 9, 9 | Nothing lies to its left and 1 to its right: sort each side the same way, the left one first.9, 9, 9, 9, 9 | 10 | 8 |
| 28 | 9, 9, 9, 9, 9 | 9 is alone in its part, so it is in place for good.9, 9, 9, 9, 9 | 10 | 8 |
| 29 | 9, 9, 9, 9, 9 | In order, after 10 comparisons and 8 swaps.9, 9, 9, 9, 9 | 10 | 8 |
In all, 10 comparisons. The formula from section 4, , gives at : the same.
where you meet it
A random pivot is one of the guards real sorts add to quick sort.
guarding quick sort's pivot
Real sorts pick the pivot at random, or as the middle of a few numbers, so a row in order is not the dearest. The books' chapter 11 lists this first among quick sort's guards, the changes that keep it from a dear run. The sort built into the programming language C++, std::sort, takes the middle in size of three numbers of the part: of 40, 10 and 25, the 25.
source: the books' volume one, chapter 11, its sidebar 'in the wild'; the GNU C++ library's stl_algo.h, as shipped with GCC 15, the part called __move_median_to_first
rows with many equal numbers
A three-way split gathers the numbers equal to the pivot in a middle part, done at once. So 5, 3, 5, 8, 5 around a 5 becomes 3, then 5, 5, 5, then 8. That removes the dear row of equal numbers, as the books' chapter 11 lists among the guards.
source: the books' volume one, chapter 11, its table of what a real sort adds
what is used instead
When the order of equal items must be kept, merge sort is used instead. When no bad luck at all is allowed, the C++ sort in GCC, an introsort, switches to heap sort after too many levels, as the quick sort page tells. Heap sort, another way to sort, has no dear row.
how it compares
Randomised quick sort beside the other ways to put a row in order, on one plot and in one table.
- bubble sort
- cocktail shaker sort
- insertion sort
- selection sort
- shell sort
- quick sort
- randomised quick sort
- merge sort
- heap sort
| way | best | average | worst | extra memory | keeps equal items in order | works in place | reach for it when |
|---|---|---|---|---|---|---|---|
| bubble sort | a few spare places (the walk number, the pair's place, whether the walk swapped, room for a number while two swap), the same however long the row | yes | yes | you are learning how sorting works; for real work, insertion sort, which on every order of up to 8 different numbers makes no more comparisons, counted order by order | |||
| cocktail shaker sort | a few spare places, the same however long the row | yes | yes | you are learning how sorting works; for real work, insertion sort | |||
| insertion sort | room for a few numbers (the number being placed, where its slide has reached, which number is next), the same however long the row | yes | yes | the row is short, a few dozen numbers, or nearly in order | |||
| selection sort | room for a few numbers (the place being filled, where the smallest so far stands, the number looked at, one held during a swap), the same however long the row | no | yes | moving a number costs far more than comparing two, and the row is short | |||
| shell sort | not known; between and | not worked out here; between and | a few spare places (the gap, the number picked up, its place), the same however long the row | no | yes | you want a few lines of code and no room beyond the row. On this site's shuffles of 200 to 10,000 numbers it averaged under a fifth of insertion sort's comparisons | |
| quick sort | a list of the parts still to sort, two memory places each. That is two places for each number on a row in order, and far fewer on a shuffle, about 51 for 100,000 numbers. So this plain version does not work in place, as its spare room grows with the row | no | no | you want a fast sort on shuffled rows with no second row, and equal items need not keep their order; use a version with a random or middle pivot | |||
| randomised quick sort | at most , as every row of different numbers averages that over the picks; a row with equal numbers can cost a little less | , a row of equal numbers, whatever the picks; no run costs more, since a pair meets at most once | a list of the parts waiting to be sorted, each kept as its first and last place. On average far shorter than the row, about 66 places for a million numbers. Unlucky picks can make it grow with the row | no | no | you want quick sort without a dear row in order, and equal items need not keep their order | |
| merge sort | a second row as long as the row | yes | no | you need comparisons growing no faster than on every row, equal items kept in order, or a file too big for memory sorted | |||
| heap sort | , every number the same | , shuffled; measured, no formula worked out here | , the dearest row; this page finds it only for short rows, by trying every order | a few places, however long the row | no | yes | you need a sort with no slow row and no second row, and equal items need not keep their order |
| counting sort | steps, every row alike | steps | steps, every row alike | a second row of n places and 10 tallies | yes | no | the numbers are small whole numbers, such as ratings from 0 to 9, and equal ones must keep their order |
| radix sort | placings, every number below 10 | placings, between the best and the worst, as every order costs the same | placings, three passes for numbers up to 999 | a second row of n places and 10 tallies | yes | no | many whole numbers with few digits, such as numbers from 0 to 999 |
- extra memory:
- the room it needs on top of the input itself, while it runs.
- keeps equal items in order:
- people sorted by age keep the order they arrived in within each age; in general, two items equal in what is being sorted come out in the order they went in.
- works in place:
- it rearranges the input where it stands, with only a few spare places, rather than building a copy; a different sense from a number being in place, in its final position.