Quick sort
how it works
The idea in a few sentences and two pictures, then one row sorted step by step.
Quick sort takes the last number of the part as its pivot. A split looks at each number but the pivot, from the left. A smaller number swaps with the first number just after the small side, so the small side grows by one. A number equal to the pivot counts as not smaller. Then the pivot swaps in just after the small side, and it is placed: nothing bigger stands before it and nothing smaller after. The numbers on each side make a part, which waits on a list to be split the same way. A part of one number is placed as it is. Sorting by splitting into smaller sorts of the same kind is called divide and conquer.
step 2 of 39
Sort the part from place 1 to place 8. Its last number, 49, is the pivot: smaller numbers go to its left.
what it remembers to know where it is
- pivot
- 49
- part starts at place
- 1
- part ends at place
- 8
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
step 7 of 39
56 is not smaller than the pivot 49, so it stays on the big side.
what it remembers to know where it is
- pivot
- 49
- part starts at place
- 1
- part ends at place
- 8
- looking at place
- 5
step 9 of 39
Swap 23 onto the small side, and 56 goes where 23 was.
what it remembers to know where it is
- pivot
- 49
- part starts at place
- 1
- part ends at place
- 8
- looking at place
- 6
step 12 of 39
Swap the pivot 49 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.
what it remembers to know where it is
- pivot
- 49
- part starts at place
- 1
- part ends at place
- 8
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
step 21 of 39
Swap the pivot 12 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.
what it remembers to know where it is
- pivot
- 12
- part starts at place
- 1
- part ends at place
- 6
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
step 39 of 39
In order, after 17 comparisons and 7 swaps.
what it remembers to know where it is
- pivot
- not yet
- part starts at place
- not yet
- part ends at place
- not yet
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
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 10
- a part of one number is in placePython lines 13 and 14
- take the part's last number as the pivotPython line 16
- look at each other number in the part, from the leftPython line 18
- if it is smaller than the pivot, swap it onto the small sidePython lines 17, 19, 20 and 21
- swap the pivot in just after the small side, where it staysPython lines 23 and 24
- sort the part on its left, then the part on its rightPython lines 11, 12, 25 and 26
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def quick_sort(numbers):
"""Put a list of numbers in order, smallest first, in the list itself.
Each part of the list is split round its last number, the pivot: every
number smaller than the pivot is swapped onto a small side at the left,
and the pivot is swapped in just after it, where it stays. Then the part
on each side of the pivot is sorted the same way, the left one first.
The parts still to sort wait on a list of their own.
"""
parts = [(0, len(numbers) - 1)] # sort the whole list as one part
while parts:
low, high = parts.pop()
if low >= high: # a part of one number, or none, is in place
continue
pivot = numbers[high] # the part's last number is the pivot
small = low # where the small side ends
for place in range(low, high): # each other number, from the left
if numbers[place] < pivot: # smaller: onto the small side
numbers[small], numbers[place] = numbers[place], numbers[small]
small += 1
# the pivot goes just after the small side, and stays there
numbers[small], numbers[high] = numbers[high], numbers[small]
parts.append((small + 1, high)) # the part on its right waits,
parts.append((low, small - 1)) # the part on its left goes first
return numbers
how it scales
How the comparisons grow, from ten numbers to ten million.
Each step across or up is ten times the one before, a log-log plot. A row already in order climbs two steps up for each step across: ten times the numbers, a hundred times the comparisons. The cheapest and the shuffled rows climb only a little more than one step.
comparisons, ten times more at each mark up
, how many numbers are in the row, ten times more at each mark to the right
- already in order, one of the dearest rowssolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
- shuffled, the average over every order of different numbers, each order as likelysolid where measured by running it; dashed where its formula carries it on to ten million
- the cheapest row, every pivot the middle in size of its partsolid where measured by running it; dashed where its formula carries it on to ten million
| 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 quick sort's comparisons yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it prints the comparisons
on a row in order, on the cheapest row, and the average over 20 shuffles.
The counts are the same on any computer; only the time taken differs.
"""
import random
class Counted:
"""A number that counts every comparison made with it."""
comparisons = 0
def __init__(self, value):
self.value = value
def __lt__(self, other):
Counted.comparisons += 1
return self.value < other.value
def quick_sort(numbers):
"""Put a list of numbers in order, smallest first, in the list itself.
Each part of the list is split round its last number, the pivot: every
number smaller than the pivot is swapped onto a small side at the left,
and the pivot is swapped in just after it, where it stays. Then the part
on each side of the pivot is sorted the same way, the left one first.
The parts still to sort wait on a list of their own.
"""
parts = [(0, len(numbers) - 1)] # sort the whole list as one part
while parts:
low, high = parts.pop()
if low >= high: # a part of one number, or none, is in place
continue
pivot = numbers[high] # the part's last number is the pivot
small = low # where the small side ends
for place in range(low, high): # each other number, from the left
if numbers[place] < pivot: # smaller: onto the small side
numbers[small], numbers[place] = numbers[place], numbers[small]
small += 1
# the pivot goes just after the small side, and stays there
numbers[small], numbers[high] = numbers[high], numbers[small]
parts.append((small + 1, high)) # the part on its right waits,
parts.append((low, small - 1)) # the part on its left goes first
return numbers
def cheapest(n, first=1):
"""The numbers first to first + n - 1, so every pivot is the middle in size."""
if n <= 0:
return []
if n == 1:
return [first]
left = (n - 1) // 2
pivot = first + left
right = cheapest(n - 1 - left, pivot + 1)
# the split moves the right part's first number to its end, so start it turned
return cheapest(left, first) + right[-1:] + right[:-1] + [pivot]
def count(row):
"""How many comparisons quick sort makes on this row."""
Counted.comparisons = 0
quick_sort([Counted(x) for x in row])
return Counted.comparisons
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>6} {'in order':>10} {'cheapest':>10} {'shuffled':>10}")
for n in [10, 100, 1000]:
shuffles = []
for _ in range(20):
row = list(range(1, n + 1))
random.shuffle(row)
shuffles.append(count(row))
in_order = count(list(range(1, n + 1)))
print(f"{n:>6} {in_order:>10} {count(cheapest(n)):>10} {sum(shuffles) / 20:>10.1f}")
extra memory, the places the sort holds beyond the row itself, ten times more at each mark up
, how many numbers are in the row, ten times more at each mark to the right
- already in order, one of the dearest rowssolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the room
- shuffled, the average over every order of different numbers, each order as likelypoints only, each measured by a real run, since no single formula for the extra memory of this row is worked out here
- the cheapest row, every pivot the middle in size of its partpoints only, each measured by a real run, since no single formula for the extra memory of this row is worked out here
best, worst and average
The same splits cost little or much, depending on the row.
A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| bestthe cheapest row, every pivot the middle in size of its part | averageshuffled, the average over every order of different numbers, each order as likely | worstalready in order, one of the dearest rows | |
|---|---|---|---|
| comparisons | |||
| how the comparisons grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: a list of the parts still to sort, two memory places each. That is two places for each number on a row in order, and far fewer on a shuffle, about 51 for 100,000 numbers. So this plain version does not work in place, as its spare room grows with the row
Extra memory is the room it needs on top of the input itself, while it runs.
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 split
the line:A row in order of 5. Each part is one shorter than the last. 4 + 3 + 2 + 1 = 10 comparisons. why it is allowed: The pivot, the last number, is the biggest. So every other number is smaller and stays on its left, in order, and nothing goes right.
guess it, thenthe move: add up the splits
the line:why it is allowed: is the comparisons on a row in order. By line 2 the parts hold , then , and on down to 2 numbers. 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 costs more
the line:why it is allowed: Two numbers meet only when one is the pivot, which then stays outside both parts, so they never meet again. On a row in order every pair meets: the bigger of the two is a pivot first, with the smaller still in its part. So counts every pair once, and no row can count more. In the picture, 5 numbers make 10 pairs.
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 7, 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 9, never drops below a quarter of .
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: count a level
the line:The cheapest row of 8, its levels placing 1, 2 and 4 numbers, then the last one. why it is allowed: A split compares every number of its part but the pivot, which it places. A part of one number is placed with no comparison. In the picture, level 0 leaves 7 numbers waiting and makes 7 comparisons; level 1 leaves 5 and makes 5.
the move: count what a level places
the line:why it is allowed: Each part places one number and makes at most two parts. So level 0 has 1 part, level 1 at most 2, level 2 at most 4, and so on.
guess it, thenthe move: count what still waits
the line:why it is allowed: By line 2, levels 0 to place at most numbers between them.
guess it, thenthe move: see the cheapest row fill its levels
the line:why it is allowed: Full means a level places all the numbers line 2 allows. Count gaps: a part has one gap more than it has numbers, one before each number and one after the last. A split keeps the gaps: 3 numbers have 4, and split round the middle one they leave 1 and 1, with 2 gaps each. A middle pivot shares the gaps as evenly as can be. So each part at level gets shared by , rounded down or up. Up to level that share is more than 2, since is at most . So each part keeps at least 2 gaps, at least one number to place. In the picture, 9 gaps become 4 and 5, then 2, 2, 2 and 3.
guess it, thenthe move: see the rest cost nothing
the line:why it is allowed: At level , shared by is at most 2, since is less than . So each part there holds one number or none. In the picture, level 3 places the 8 alone.
guess it, thenthe move: see such a row for every n
the line:why it is allowed: Put the middle number last and build each side the same way. The split keeps the small side as it is, and the pivot swaps with the big side's first number, which goes to the end. So write the big side with its last number first: to get 5, 7, 8, 6 after the split, write 6, 5, 7, 8. For 8 numbers: 1, 3, 2, then 6, 5, 7, 8, then 4, as in the picture.
guess it, thenthe move: add the levels
the line:why it is allowed: is the comparisons on the cheapest row. By lines 1 and 3, no row's levels 0 to compare fewer than these. By lines 4 to 6, the row with every pivot in the middle compares just these.
guess it, thenthe move: add each doubling
the line:where does this come from?
question 1 of the page doubling and halving sumsAdd . What is the total? the move: name the sum
the line:why it is allowed: Let be the doubling sum up to . For as 3, it is 1 + 2 + 4 + 8.
the move: double both sides
the line:why it is allowed: Each term doubled is the next one along, and becomes . Doubling both sides keeps them equal. The plan: the two sums share all but their ends.
the move: take line 1 away
the line:why it is allowed: Take from both sides of line 2. On the right, write out as line 1 does.
the move: tidy the left side
the line:why it is allowed: Two lots of less one lot is one lot.
the move: cancel what both brackets share
the line:when n is 3 1 2 4 8 16 first bracket 2 4 8 16 second bracket 1 2 4 8 left over take away 1 16 Line 4 when is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15. why it is allowed: Every term from 2 to is in both brackets and cancels, leaving less 1.
the move: the terms before the last
the line:why it is allowed: The sum of line 5 stopping one term sooner: line 5 with for . For 3, it is 1 + 2 + 4. At as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.
the move: tidy the power
the line:why it is allowed: One more than is . For 3, 1 + 2 + 4 is 7, one less than 8.
the move: read it
the line:why it is allowed: By lines 6 and 7, the terms before the last add to one less than it: the last outweighs them all. By line 5 the sum is under , twice the last.
why it is allowed: The doublings 1, 2, 4 and on add up to one less than the next doubling, as the fold shows. So 1 + 2 is 3, and 1 + 2 + 4 is 7. For 8 numbers, L is 3 and B is 7 + 5 + 1, which is 13.
guess it, thenthe move: write each term with n + 1
the line:why it is allowed: Taking away one less than a power of 2 is taking away the power and adding 1, so is . There are terms.
guess it, thenthe move: gather the n + 1s
the line:why it is allowed: The terms of line 9 each hold one .
guess it, thenthe move: add the doublings again
the line:why it is allowed: By the fold at line 8, the doublings from 1 add up to one less than the next doubling. Here the first 1 is missing, so it is two less. For 8 numbers, 2 + 4 + 8 is 14, which is 16 less 2.
guess it, thenthe move: open the bracket
the line:why it is allowed: Taking away a bracket takes away each thing in it. For 8 numbers, 9 times 3, less 16, plus 2, is 13, as in the picture.
guess it, thenthe move: a ceiling
the line:why it is allowed: Each of the terms of line 9 is less a power of 2, at least 2, so each is less than .
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: is at most .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 14.
guess it, thenthe move: a floor
the line:why it is allowed: is at most , so is at most half of . So each term of line 9 but the last is more than half of , and the last is at least 1. From 2 numbers on, line 9 has at least one term. For 8 numbers, 4 is half of 8.
guess it, thenthe move: leave out the 1
the line:why it is allowed: Taking 1 away from the floor of line 16 leaves a floor.
guess it, thenthe move: a floor with logs only
the line:why it is allowed: is the whole part of , so it is more than less 1, and is more than .
guess it, thenthe move: what 8 numbers allow
the line:why it is allowed: From 8 numbers on, is at least 3, so 2 is at most two thirds of it, and taking 2 away leaves at least a third. At 8, 3 less 2 is 1, exactly a third of 3.
guess it, thenthe move: a simpler floor
the line:why it is allowed: Put line 19 into line 18.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 20.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 15 and 21 bound by the same growth, .
guess it, then
try it with a small : at , line 7 gives , which you can work out by hand
the move: name the numbers
the line:why it is allowed: Only the order of the numbers matters to the splits, so any different numbers act like 1 to .
the move: watch two numbers
the line: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.
guess it, thenthe move: a number between parts them
the line:The yellow triangles follow 2 and 5. The 3, between them, is the first of 2 to 5 to be a pivot, so they part without meeting. why it is allowed: That pivot sends left and right, into different parts, and it is neither of them. In the picture, the 3 parts 2 and 5.
guess it, thenthe move: an end meets the other
the line:The same shuffle with the 3 and the 5 traded. Now 5 is the first of 2 to 5 to be a pivot, and its split compares 2 with it. why it is allowed: By line 2 the other is still in its part, so the split compares them. The pivot is then placed, outside both parts, so they never meet again. In the picture, 5 comes first and meets 2.
guess it, thenthe move: see each come first equally often
the line:order first pivot 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 1, 3, 2 2 1 0 1 2 3, 1, 2 2 1 0 1 2 2, 3, 1 1 1 1 1 3 3, 2, 1 1 1 1 1 3 in all 6 4 6 16 Every order of 1, 2 and 3, each as likely, with a 1 where a pair meets. A row's comparisons are its 1s added up. why it is allowed: Trade the places of two numbers from to , as the pictures at lines 3 and 4 trade the 3 and the 5. Every split before one of them is a pivot stays the same. The first of them to be a pivot is taken from the same place, now holding the other number. So each of the numbers comes first equally often. By lines 3 and 4, the pair meets when it is or . In the table, each of 1, 2 and 3 comes first in 2 of the 6 orders, so 1 and 3 meet in 4.
guess it, thenthe move: count the pairs k apart
the line:why it is allowed: Two numbers stand apart when the bigger is the smaller plus . Each of 1, 2, and on up to has a partner above it. With 4 numbers, 3 pairs stand 1 apart. From to there are then numbers, so line 5 gives 2 in .
guess it, thenthe move: average pair by pair
the line:why it is allowed: is the comparisons averaged over every shuffle. A shuffle's comparisons are the pairs that meet in it, each once by line 4. Adding every shuffle's comparisons counts each pair once for each shuffle where it meets. Dividing by the shuffles gives each pair's share, from line 6. In the table: 6 + 4 + 6 is 16 comparisons over 6 orders, or 1, plus 2 thirds, plus 1.
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 less 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: gather the terms
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, 2 times 4 times 11 sixths, less 12, is 16 over 6, the table's average.
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.
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.
guess it, thenthe move: a floor from the cheapest row
the line:why it is allowed: No shuffle costs less than the cheapest row, so neither does their average. The cheapest row costs at least this, by line 20 of the question on the cheapest row, in section 4 of the learn page.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 21.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 20 and 22 bound by the same growth, .
guess it, then
try it on small rows: over every order of 8 numbers, the average is about 16.92
the move: the list of waiting parts
the line:after parts waiting parts the start places 1 to 5 1 splitting 1 to 5 an empty part, places 1 to 4 2 splitting 1 to 4 2 empty parts, places 1 to 3 3 splitting 1 to 3 3 empty parts, places 1 to 2 4 splitting 1 to 2 4 empty parts, place 1 5 A row in order of 5. Each split leaves an empty right part waiting, so the list grows by one part each time, to 5 parts. why it is allowed: Each waiting part takes two memory places, one for where it starts in the row and one for where it ends. The left part is taken off first. An empty part is put on too, and dropped when it is taken off.
the move: in order, the list only grows
the line:why it is allowed: By line 2 of the first ladder, nothing goes right of a pivot, and the left part is taken off next.
guess it, thenthe move: count the places
the line:why it is allowed: is the most memory places taken at once. The list starts with the whole row. A row in order takes splits, by line 3 of the first ladder, and by lines 1 and 2 each adds a part, two places each.
guess it, thenthe move: tidy
the line:why it is allowed: For 5 numbers, 5 parts, 10 places.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
count it yourself
Count every comparison on the cheapest row of 5 numbers. For 5 numbers is 2, so the formula gives 6 times 2, less 8, plus 2, which is 6.
| step | the row | what happens | comparisons | swaps |
|---|---|---|---|---|
| 1 | 2, 1, 4, 5, 3 | There are 5 numbers in a row. Sort the whole row as one part.2, 1, 4, 5, 3 | 0 | 0 |
| 2 | 2, 1, 4, 5, 3 | Sort the part from place 1 to place 5. Its last number, 3, is the pivot: smaller numbers go to its left.2, 1, 4, 5, 3 | 0 | 0 |
| 3 | 2, 1, 4, 5, 3 | 2 is smaller than the pivot 3, and it already stands at the end of the small side.2, 1, 4, 5, 3 | 1 | 0 |
| 4 | 2, 1, 4, 5, 3 | 1 is smaller than the pivot 3, and it already stands at the end of the small side.2, 1, 4, 5, 3 | 2 | 0 |
| 5 | 2, 1, 4, 5, 3 | 4 is not smaller than the pivot 3, so it stays on the big side.2, 1, 4, 5, 3 | 3 | 0 |
| 6 | 2, 1, 4, 5, 3 | 5 is not smaller than the pivot 3, so it stays on the big side.2, 1, 4, 5, 3 | 4 | 0 |
| 7 | 2, 1, 3, 5, 4 | Swap the pivot 3 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.2, 1, 3, 5, 4 | 4 | 1 |
| 8 | 2, 1, 3, 5, 4 | 2 numbers lie to its left and 2 to its right: sort each side the same way, the left one first.2, 1, 3, 5, 4 | 4 | 1 |
| 9 | 2, 1, 3, 5, 4 | Sort the part from place 1 to place 2. Its last number, 1, is the pivot: smaller numbers go to its left.2, 1, 3, 5, 4 | 4 | 1 |
| 10 | 2, 1, 3, 5, 4 | 2 is not smaller than the pivot 1, so it stays on the big side.2, 1, 3, 5, 4 | 5 | 1 |
| 11 | 1, 2, 3, 5, 4 | Swap the pivot 1 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.1, 2, 3, 5, 4 | 5 | 2 |
| 12 | 1, 2, 3, 5, 4 | Nothing lies to its left and 1 to its right: sort each side the same way, the left one first.1, 2, 3, 5, 4 | 5 | 2 |
| 13 | 1, 2, 3, 5, 4 | 2 is alone in its part, so it is in place for good.1, 2, 3, 5, 4 | 5 | 2 |
| 14 | 1, 2, 3, 5, 4 | Sort the part from place 4 to place 5. Its last number, 4, is the pivot: smaller numbers go to its left.1, 2, 3, 5, 4 | 5 | 2 |
| 15 | 1, 2, 3, 5, 4 | 5 is not smaller than the pivot 4, so it stays on the big side.1, 2, 3, 5, 4 | 6 | 2 |
| 16 | 1, 2, 3, 4, 5 | Swap the pivot 4 in just after the small side. Nothing to its left is bigger and nothing to its right is smaller, so it stays there for good.1, 2, 3, 4, 5 | 6 | 3 |
| 17 | 1, 2, 3, 4, 5 | Nothing lies to its left and 1 to its right: sort each side the same way, the left one first.1, 2, 3, 4, 5 | 6 | 3 |
| 18 | 1, 2, 3, 4, 5 | 5 is alone in its part, so it is in place for good.1, 2, 3, 4, 5 | 6 | 3 |
| 19 | 1, 2, 3, 4, 5 | In order, after 6 comparisons and 3 swaps.1, 2, 3, 4, 5 | 6 | 3 |
In all, 6 comparisons. The formula from section 4, , gives at : the same.
where you meet it
Quick sort, with a few guards added, is inside many standard sorts.
the C++ library's sort
C++ is a programming language. In the library that comes with the GNU compiler, its standard sort, std::sort, is introsort. It splits like quick sort, taking as pivot the middle in size of the part's second, middle and last numbers. If the parts go more than twice levels deep, it switches to heap sort, which has no bad row. Insertion sort finishes stretches of 16 or fewer.
source: the GNU C++ library's stl_algo.h (__sort, __introsort_loop, __move_median_to_first, __final_insertion_sort) and stl_algobase.h (__lg), GCC 15. Heap sort having no bad case, the books' volume one, chapter 11
finding the middle value
The same library's std::nth_element finds the number that belongs at one place, such as the middle, without sorting the rest. It splits like quick sort, but then works on only the part holding that place.
source: the GNU C++ library's file stl_algo.h, as shipped with GCC 15, the parts called nth_element and __introselect
what is used instead
This page's quick sort is the plain one. Real sorts add guards, as Sebastian Bourges' books, Algorithmic Thinking Without the Jargon, list in volume one, chapter 11. A random or middle pivot keeps a row in order from being the dearest. Insertion sort finishes the short parts. Sorting the smaller part first keeps the list of waiting parts short. Quick sort can swap equal numbers: sorting 4, 4, 9 ends with the two 4s swapped, as the second 4 is a pivot and swaps in front of the first. When equal items must keep the order they came in, merge sort is used instead.
how it compares
Quick sort beside the other ways to put a row in order, on one plot and in one table.
- 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.