Merge sort
how it works
The idea and three pictures, then one row sorted step by step.
Merge sort puts a row of numbers in order, smallest first. A run is a part of the row in order, and one number alone is a run. A merge joins two runs. It places the smaller front into a second row, the left one on a tie. When one run is used up, the rest of the other follows with no comparison. Round 1 merges runs of 1 in pairs from the left, round 2 runs of 2, and on, building bottom up until one run holds the row. A run with no partner waits. The steps below draw each merge in the one row.
| round | run length | merges | comparisons | placed |
|---|---|---|---|---|
| 1 | 1 | 4 | 4 | 8 |
| 2 | 2 | 2 | 6 | 8 |
| 3 | 4 | 1 | 6 | 8 |
| in all | 7 | 16 | 24 |
step 1 of 44
There are 8 numbers in a row. Each one on its own is a run in order.
what it remembers to know where it is
- run length
- not yet
- front of the left run
- not yet
- front of the right run
- not yet
Where it says not yet, nothing is held there at that moment.
step 4 of 44
7 is smaller than 42, so 7 goes next.
what it remembers to know where it is
- run length
- 1
- front of the left run
- 42
- front of the right run
- 7
step 5 of 44
7 moves in front of 42, and the left run moves one place right to make room.
what it remembers to know where it is
- run length
- 1
- front of the left run
- 42
- front of the right run
- 7
step 18 of 44
Merge neighbouring runs of up to 2 numbers into runs of up to 4.
what it remembers to know where it is
- run length
- 2
- front of the left run
- not yet
- front of the right run
- not yet
Where it says not yet, nothing is held there at that moment.
step 33 of 44
Merge neighbouring runs of up to 4 numbers into runs of up to 8.
what it remembers to know where it is
- run length
- 4
- front of the left run
- not yet
- front of the right run
- not yet
Where it says not yet, nothing is held there at that moment.
step 37 of 44
12 moves in front of 18, and the left run moves one place right to make room.
what it remembers to know where it is
- run length
- 4
- front of the left run
- 18
- front of the right run
- 12
step 43 of 44
One run is used up, so the 2 numbers left in the other follow as they stand.
what it remembers to know where it is
- run length
- 4
- front of the left run
- not yet
- front of the right run
- not yet
Where it says not yet, nothing is held there at that moment.
step 44 of 44
In order, after 16 comparisons, with 24 numbers placed into merged runs.
what it remembers to know where it is
- run length
- not yet
- front of the left run
- not yet
- front of the right run
- 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
- every number on its own is a run in orderPython lines 12, 13 and 15
- while there is more than one runPython lines 16, 40, 41 and 42
- merge each neighbouring pair of runs into onePython lines 11, 14, 17, 18, 19, 20 and 21
- compare the fronts of the two runsPython lines 23 and 24
- the smaller goes next, the left one if they are equalPython lines 25, 26, 27, 28, 29 and 30
- when one run is used up, the rest of the other followsPython lines 32, 33, 34, 35, 36, 37, 38 and 39
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 merge_sort(numbers):
"""Put a list of numbers in order, smallest first, ending in the same list.
Every number on its own is a run in order. Neighbouring runs are merged
into runs twice as long, round after round, until one run holds the
whole list. Each round writes into a second list as long as the first,
made once and used again every round, so the sort needs that much room
again. On a tie the number from the left run goes first, so equal
numbers keep the order they came in.
"""
n = len(numbers)
if n < 2: # one number, or none, is already in order
return numbers
merged = [None] * n # the second list, used again every round
width = 1 # every number on its own is a run in order
while width < n: # while there is more than one run
for start in range(0, n, 2 * width): # each pair of runs,
# or a last run with no partner, copied across as it stands
middle = min(start + width, n)
end = min(start + 2 * width, n)
i, j, k = start, middle, start # the two fronts, the next place
while i < middle and j < end: # compare the two fronts
if numbers[j] < numbers[i]: # the smaller goes next,
merged[k] = numbers[j]
j += 1
else: # the left one if they are equal
merged[k] = numbers[i]
i += 1
k += 1
while i < middle: # one run is used up: the rest of the other
merged[k] = numbers[i]
i += 1
k += 1
while j < end:
merged[k] = numbers[j]
j += 1
k += 1
for k in range(n): # the round's runs, twice as long, copied back
numbers[k] = merged[k]
width *= 2
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 lines climb a little more than one step up for each step across, as outgrows . The shuffled points, the mean of 20 shuffles each, lie just under the dearest line.
comparisons, ten times more at each mark up
, how many numbers are in the row, ten times more at each mark to the right
- a dearest row, where every merge compares all but its last numbersolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, 12 times the work
- shuffled, every order of different numbers as likelypoints only, each measured by a real run, since no single formula for the comparisons of this row is worked out here
- different numbers back to front, a cheapest rowsolid where measured by running it; dashed where its formula carries it on to ten million
| comparisons | time | |
|---|---|---|
| 1,000 | 8,985 | about 9 microseconds |
| 100,000 | 1,592,993 | about 1.6 milliseconds |
| 10,000,000 | 226,648,193 | about 227 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.
"""Count merge 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 back to front (a cheapest row), on a row already in order, 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 merge_sort(numbers):
"""Put a list of numbers in order, smallest first, ending in the same list.
Every number on its own is a run in order. Neighbouring runs are merged
into runs twice as long, round after round, until one run holds the
whole list. Each round writes into a second list as long as the first,
made once and used again every round, so the sort needs that much room
again. On a tie the number from the left run goes first, so equal
numbers keep the order they came in.
"""
n = len(numbers)
if n < 2: # one number, or none, is already in order
return numbers
merged = [None] * n # the second list, used again every round
width = 1 # every number on its own is a run in order
while width < n: # while there is more than one run
for start in range(0, n, 2 * width): # each pair of runs,
# or a last run with no partner, copied across as it stands
middle = min(start + width, n)
end = min(start + 2 * width, n)
i, j, k = start, middle, start # the two fronts, the next place
while i < middle and j < end: # compare the two fronts
if numbers[j] < numbers[i]: # the smaller goes next,
merged[k] = numbers[j]
j += 1
else: # the left one if they are equal
merged[k] = numbers[i]
i += 1
k += 1
while i < middle: # one run is used up: the rest of the other
merged[k] = numbers[i]
i += 1
k += 1
while j < end:
merged[k] = numbers[j]
j += 1
k += 1
for k in range(n): # the round's runs, twice as long, copied back
numbers[k] = merged[k]
width *= 2
return numbers
def cheapest(n):
"""The numbers n down to 1, back to front: every merge compares only its right run."""
return list(range(n, 0, -1))
def count(row):
"""How many comparisons merge sort makes on this row."""
Counted.comparisons = 0
merge_sort([Counted(x) for x in row])
return Counted.comparisons
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>6} {'back to front':>14} {'in order':>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} {count(cheapest(n)):>14} {in_order:>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
- every row, whatever its ordersolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the room
best, worst and average
Every row of 8 places 24, whatever its order; only the comparisons change. By the page on the sorting floor, every sort that only compares, with no random choices, has dearest rows whose cost grows at least as fast as . Merge sort's grow just that fast.
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.
| bestdifferent numbers back to front, a cheapest row | averageshuffled, every order of different numbers as likely | worsta dearest row, where every merge compares all but its last number | |
|---|---|---|---|
| comparisons | , each round's right run lengths added up | between the best and the worst | |
| numbers placed | , the same on every row | , the same on every row | , the same on every row |
| how the comparisons grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: a second row as long as the row
Extra memory is the room it needs on top of the input itself, while it runs.
| row of 8 | numbers | comparisons | placed |
|---|---|---|---|
| back to front | 8 down to 1 | 12 | 24 |
| in order | 1 up to 8 | 12 | 24 |
| on average | all 40,320 orders | about 15.73 | 24 |
| dearest | 1, 5, 3, 7, 2, 6, 4, 8 | 17 | 24 |
| row of 9 | round 1 | round 2 | round 3 | round 4 | in all |
|---|---|---|---|---|---|
| in order | 4 | 4 | 4 | 8 | 20 |
| back to front | 4 | 4 | 4 | 1 | 13 |
where the formula comes from
Five ladders, one for each count in section 3, climb in small steps, each naming the line it uses.
the move: the runs at the start of a round
the line:Runs of 1, then 2, 2, 2 and 1, then 4 and 3, then 7. why it is allowed: Round 1 starts from runs of 1, and merging in pairs from the left doubles them, as drawn. The last run may be shorter.
the move: cut the round into stretches
the line:why it is allowed: By line 1, a merge takes places. Only the last stretch can be short, and with or fewer it is a left run alone.
guess it, thenthe move: what each stretch places
the line:run length stretches waits placed 1 1 to 2, 3 to 4, 5 to 6, 7 the 7th 6 2 1 to 4, 5 to 7 none 7 4 1 to 7 none 7 The rounds on 7 numbers, 6 + 7 + 7 = 20 placed. why it is allowed: A merge writes each of its numbers into the second row once. A left run alone waits; the Python copies it across, but no merge places it.
guess it, thenthe move: which rounds there are
the line:why it is allowed: By line 1, places 1 to hold one run, so a second run, and so a round, exists exactly when is below . For 7 numbers, 1, 2 and 4, not 8.
guess it, thenthe move: add up the rounds
the line:why it is allowed: is the numbers placed in all, those in the round with run length ; one term a round, by line 4. For 7 numbers, 6 + 7 + 7 = 20.
guess it, thenthe move: the same on every row
the line:why it is allowed: By lines 2 and 3, what a round places depends on and alone, never on the order. For 8 numbers, 24 on every order.
guess it, thenthe move: a ceiling for each term
the line:why it is allowed: By line 3 a round places each number once at most.
guess it, thenthe move: add up the ceilings
the line:why it is allowed: counts the rounds. By lines 5 and 7, terms, each at most . For 7 numbers, 20 is at most 21.
guess it, thenthe move: number the rounds
the line:why it is allowed: Round 1 has run length 1, 2 to the power 0, and each round doubles it.
guess it, thenthe move: the last round's run length
the line:why it is allowed: By line 9 the last round, round , has run length , below by line 4.
guess it, thenthe move: take the log to base 2 of both sides
the line:7 lies between 4 and 8, its log between 2 and 3. why it is allowed: In line 10, the log of is , and a bigger number has a bigger log. For 7 numbers, 2 is at most about 2.81.
guess it, thenthe move: add 1 to both sides
the line:why it is allowed: Line 11 plus 1.
guess it, thenthe move: multiply both sides by n
the line:why it is allowed: Line 12 times , more than zero.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: Lines 8 and 13. For 7 numbers, 20 is at most about 26.65.
guess it, thenthe move: from 2 numbers on, the log is at least 1
the line:why it is allowed: The log of 2 is 1, and a bigger number has a bigger log.
guess it, thenthe move: add the log to both sides
the line:why it is allowed: Line 15 plus .
guess it, thenthe move: add like to like
the line:why it is allowed: In line 16, a log plus the same log is twice it.
guess it, thenthe move: multiply both sides by n again
the line:why it is allowed: Line 17 times .
guess it, thenthe move: a simpler ceiling still
the line:why it is allowed: Lines 14 and 18. For 7 numbers, 20 is at most about 39.30.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 19, at most 2 times .
guess it, thenthe move: the next run length is not below n
the line:why it is allowed: Now a floor. The next run length, by line 9, would make another round by line 4 if it were below . For 7 numbers, 7 is at most 8.
guess it, thenthe move: halve both sides of line 10
the line:why it is allowed: Halving both sides keeps it true. For 7 numbers, 2 is at most 3.5.
guess it, thenthe move: what a round leaves out
the line:why it is allowed: By line 3 a round leaves out at most a left run alone, places or fewer.
guess it, thenthe move: a round before the last has a short run length
the line:why it is allowed: By line 9 its run length is at most , so by line 22 at most half of .
guess it, thenthe move: so it places at least half the row
the line:why it is allowed: By lines 23 and 24, less at most half of .
guess it, thenthe move: the last round places every number
the line:why it is allowed: By lines 4 and 21 its run length is below and twice it is not, so by lines 2 and 3 it merges the whole row. For 7 numbers, 1 to 4 with 5 to 7.
guess it, thenthe move: add up the rounds again, from below
the line:why it is allowed: Line 5, with lines 25 and 26; with 2 numbers no round comes before the last.
guess it, thenthe move: a simpler floor
the line:why it is allowed: In line 27, is at least half of .
guess it, thenthe move: tidy the floor
the line:why it is allowed: In line 28, halves and one more make halves.
guess it, thenthe move: take the log to base 2 of both sides of line 21
the line:why it is allowed: The log of is , and a bigger number has a bigger log.
guess it, thenthe move: multiply both sides by half of n
the line:why it is allowed: Line 30 times half of .
guess it, thenthe move: a simpler floor still
the line:why it is allowed: Lines 29 and 31. For 7 numbers, 20 is at least about 9.83.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 32, at least half of .
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 20 and 33 bound by the same growth. For 8 numbers, is 24, as is 8 times 3.
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
the move: a merge compares at least the run used up first
the line:why it is allowed: Each comparison places one number, and a merge compares only while both runs hold numbers. So each number of the run used up first took one. Merging 7, 42 with 18, 31, the 18 and 31 did.
the move: the right run is never longer
the line:why it is allowed: By the first ladder's line 2, a left run is a full , and the right run at most .
guess it, thenthe move: so a merge compares at least its right run's length
the line:why it is allowed: By line 1. The run used up first is the right run, or the left, which holds at least as many by line 2.
guess it, thenthe move: on a row back to front, each run is below the runs to its left
the line:Round 2 merges 5, 6 with 3, 4 into 3, 4, 5, 6. after the round with run length the row none yet 6, 5, 4, 3, 2, 1 1 5, 6, 3, 4, 1, 2 2 3, 4, 5, 6, 1, 2 4 1, 2, 3, 4, 5, 6 Every run stays below each run to its left. why it is allowed: Back to front, each number is below every number to its left. A merge only reorders its own stretch, so its run stays below the runs to its left.
guess it, thenthe move: so each merge compares exactly its right run's length
the line:why it is allowed: By line 4 each comparison places a number of the right run, until it is used up. Then the left follows. Merging 5, 6 with 3, 4: 2 comparisons.
guess it, thenthe move: add up the merges
the line:why it is allowed: is the comparisons back to front, what the right runs hold in the round with run length , by line 5. The rounds are the first ladder's line 4. For 7 numbers, 3 + 3 + 3 = 9.
guess it, thenthe move: no row costs fewer
the line:why it is allowed: By the first ladder's lines 2 and 4, every row of has the same merges, and by line 3 above each compares at least its right run. Equal numbers may cost more, as 3, 2, 2, 1 costs 5, not 4.
guess it, thenthe move: a right run is at most half its merge
the line:why it is allowed: By line 2.
guess it, thenthe move: add up the halves
the line:why it is allowed: Lines 6 and 8 above; the merges' numbers add up to , by the first ladder's line 5.
guess it, thenthe move: halve both sides of the first ladder's ceiling
the line:why it is allowed: The first ladder's line 19, halved.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: Lines 9 and 10. For 7 numbers, 9 is at most about 19.65.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 11, at most itself.
guess it, thenthe move: the places the full stretches cover
the line:why it is allowed: Now a floor, adding only rounds with run length at most a quarter of . Only the last stretch can be short, so the full ones cover more than . For 9 numbers and run length 2, 8 places, more than 5.
guess it, thenthe move: half of them are right runs
the line:why it is allowed: A full stretch is a left run and a right run of each, by the first ladder's line 2. With line 13 above, the right runs hold more than half of .
guess it, thenthe move: halve
the line:why it is allowed: In line 14, half of is .
guess it, thenthe move: the round's right runs
the line:why it is allowed: Lines 14 and 15, as may also count a short last stretch's right run.
guess it, thenthe move: a round with a short run length
the line:run length 4.5 less it the right runs hold kept, run length at most 2.25 1 3.5 4 yes, kept 2 2.5 4 yes, kept 4 0.5 4 no 8 below 0 1 no 9 back to front; 4.5 is half of 9, 2.25 a quarter. why it is allowed: Then is at least a quarter of , and is more, by line 16. For 9 numbers and run length 2, 4 is at least 2.25.
guess it, thenthe move: name the longest short run length
the line:why it is allowed: The kept run lengths are powers of 2. From 4 numbers on a quarter of is at least 1, so exists. For 9 numbers, is 1, keeping 1 and 2.
guess it, thenthe move: count the rounds with a short run length
the line:why it is allowed: The run lengths 1, 2 and on up to are at most a quarter of , by line 18. So they are below , and rounds by the first ladder's line 4.
guess it, thenthe move: the next power of 2 is too big
the line:why it is allowed: By line 18, is the largest.
guess it, thenthe move: take the log to base 2 of both sides
the line:why it is allowed: In line 20, the log of is , and a bigger number has a bigger log.
guess it, thenthe move: twice a half
the line:why it is allowed: Doubling adds 1 to a log, as question 1, line 2 of the page on growth and the growth ladder shows for any number from 1. From 4 numbers on, half of is at least 2.
guess it, thenthe move: twice a quarter
the line:why it is allowed: Line 22's fact for a quarter of , at least 1 from 4 numbers on.
guess it, thenthe move: put line 23 into line 22, then take 2 from both sides
the line:why it is allowed: Line 23 in line 22 makes 2 more than the log of a quarter of . Take 2 from both sides. For 8 numbers, 1 is 3 less 2.
guess it, thenthe move: put lines 21 and 24 together
the line:why it is allowed: More than, so at least.
guess it, thenthe move: add up those rounds alone
the line:why it is allowed: No term of line 6 is below zero, so the short rounds alone give no more. Line 19 counts them, each at least a quarter of by line 17. For 8 numbers, 12 is at least 4.
guess it, thenthe move: multiply both sides of line 25 by a quarter of n
the line:why it is allowed: A quarter of is more than zero.
guess it, thenthe move: put the two together
the line:why it is allowed: Lines 26 and 27. For 8 numbers, 12 is at least 2.
guess it, thenthe move: from 8 numbers on, the log is at least 3
the line:why it is allowed: The log of 8 is 3, and a bigger number has a bigger log.
guess it, thenthe move: multiply both sides by two thirds
the line:why it is allowed: Line 29 times two thirds, as two thirds of 3 is the 2 of line 28.
guess it, thenthe move: take more away
the line:why it is allowed: By line 30, two thirds of the log is at least 2, and taking more away leaves less.
guess it, thenthe move: tidy
the line:why it is allowed: In line 31, a whole log less two thirds of it is a third.
guess it, thenthe move: multiply both sides by a quarter of n
the line:why it is allowed: Line 32 times a quarter of .
guess it, thenthe move: tidy
the line:why it is allowed: In line 33, a third times a quarter is a twelfth.
guess it, thenthe move: a simpler floor
the line:why it is allowed: Lines 28 and 34. For 8 numbers, 12 is at least 2.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 35, at least a twelfth of from 8 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 12 and 36 bound by the same growth. For 8 numbers, is 12.
guess it, then
try it with a small : at , line 6 gives , which you can work out by hand
the move: a merge places its last number with no comparison
the line:Round 2 merges 7, 31 with 18, 42 into 7, 18, 31, 42. why it is allowed: and are the runs' lengths. Each comparison places one number. The comparison that uses up one run leaves a number in the other, which follows with none. Merging 7, 31 with 18, 42: 3 comparisons.
the move: count the merges
the line:why it is allowed: Each merge turns two runs into one, and a run that waits stays one. So runs need merges. For 8 numbers, 4 + 2 + 1.
guess it, thenthe move: add up the merges
the line:why it is allowed: Line 1 for each merge, the numbers adding up to by the first ladder's line 5, and line 2 above counting the merges. For 8 numbers, 24 less 7, 17.
guess it, thenthe move: when a merge runs to its last pair
the line:why it is allowed: The next largest ends its run, so that run lasts until all but the largest are placed. The largest waits in the other run all along, so each placing took a comparison. Merging 7, 31 with 18, 42: 3.
guess it, thenthe move: the last merge's two parts
the line:why it is allowed: By the first ladder's lines 9, 4 and 21, the last run length, , is below and twice it is not. So by the first ladder's line 2 the last stretch is the whole row. For 8 numbers, 1 to 4 and 5 to 8.
guess it, thenthe move: earlier merges stay inside one part
the line:why it is allowed: By the first ladder's line 9, an earlier stretch, places, is a power of 2 up to the left part's . So these stretches fill places 1 to exactly, and none crosses. For 7 numbers, 1 to 4 holds two stretches of 2, then one of 4.
guess it, thenthe move: each part is merged as a row of its own
the line:why it is allowed: By line 6 each part is cut as a row of its own. Its own rounds have run lengths 1, 2, 4 and on, below its length, by the first ladder's line 4. Each part holds at most , by line 5, so these come before the last round, by the first ladder's line 9. In other rounds a short part waits, as the 9th of 9 does.
guess it, thenthe move: build a row where every merge runs to its last pair
the line:Round 3 merges 1, 3, 5, 7 with 2, 4, 6, 8, from each run in turn. the numbers the left part gets the right part gets 1 to 8 7, 5, 3, 1 8, 6, 4, 2 7, 5, 3, 1 5, 1 7, 3 8, 6, 4, 2 6, 2 8, 4 5, 1 1 5 7, 3 3 7 6, 2 2 6 8, 4 4 8 Largest first, right first; the bottom four lines give 1, 5, 3, 7, 2, 6, 4, 8. why it is allowed: By line 5 the right part is never the longer; once it is full, the rest go left. The two largest stand apart, so by line 4 the last merge makes . Lines 6 and 7 let each part be dealt the same way.
guess it, thenthe move: add up that row's merges
the line:why it is allowed: Line 8 in every merge, added up as in line 3.
guess it, thenthe move: the most any row costs
the line:why it is allowed: is the comparisons on a dearest row. Line 3 caps every row, and the row of line 9 reaches the cap.
guess it, thenthe move: a ceiling
the line:why it is allowed: In line 10, is not below 0.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: Line 11 above and the first ladder's line 19.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 12, at most 2 times .
guess it, thenthe move: a floor
the line:why it is allowed: Now a floor, putting the first ladder's line 32 into line 10 above.
guess it, thenthe move: take away a little more
the line:why it is allowed: In line 14, is more than .
guess it, thenthe move: from 8 numbers on, the log is at least 3
the line:why it is allowed: The log of 8 is 3, and a bigger number has a bigger log.
guess it, thenthe move: multiply both sides by a third of n
the line:why it is allowed: Line 16 times a third of , as a third of times 3 is .
guess it, thenthe move: take more away still
the line:why it is allowed: By line 17 the right side takes away at least .
guess it, thenthe move: put the two together
the line:why it is allowed: Lines 15 and 18.
guess it, thenthe move: tidy the floor
the line:why it is allowed: In line 19, a half less a third is a sixth. For 8 numbers, 17 is at least 4.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 20, at least a sixth of from 8 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 13 and 21 bound by the same growth.
guess it, then
try it with a small : at , line 10 gives , which you can work out by hand
the move: at least the cheapest row
the line:row cheapest on average dearest 8 numbers 12 about 15.73, every order 17 1,000 numbers 4,932 about 8,720, 20 shuffles 8,985 The average lies between, nearer the dearest. why it is allowed: is the average over every order of different numbers, estimated in section 2 from 20 shuffles. No row costs less than , by the second ladder's line 7, so neither does an average.
the move: the second ladder's floor
the line:why it is allowed: The second ladder's line 35, with line 1 above.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 2.
guess it, thenthe move: at most the dearest row
the line:why it is allowed: By the third ladder's lines 3 and 10, no row costs more than , so neither does an average.
guess it, thenthe move: the third ladder's ceiling
the line:why it is allowed: The third ladder's line 12, with line 4 above.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 3 and 6 bound by the same growth, with no formula needed.
guess it, then
try it on small rows: over every order of 8 numbers, the average is about 15.73
the move: the second row
the line:fronts compared placed the second row so far 7 and 18 7 7 42 and 18 18 7, 18 42 and 31 31 7, 18, 31 none, the right run is used up 42 7, 18, 31, 42 Merging 7, 42 with 18, 31 into the second row. why it is allowed: Each round writes its runs into a second row of places, then copies them back, so the next round uses it again.
the move: count the places
the line:why it is allowed: By line 1, is the second row's places, whatever the order. The few spare places, such as the run length, do not grow.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 3 and 4.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
count it yourself
Follow every step on 6 numbers.
| step | the row | what happens | comparisons | numbers placed |
|---|---|---|---|---|
| 1 | 45, 13, 62, 6, 33, 28 | There are 6 numbers in a row. Each one on its own is a run in order.45, 13, 62, 6, 33, 28 | 0 | 0 |
| 2 | 45, 13, 62, 6, 33, 28 | Merge neighbouring runs of 1 number into runs of up to 2.45, 13, 62, 6, 33, 28 | 0 | 0 |
| 3 | 45, 13, 62, 6, 33, 28 | Merge the run that starts at place 1 with the one that starts at place 2.45, 13, 62, 6, 33, 28 | 0 | 0 |
| 4 | 45, 13, 62, 6, 33, 28 | 13 is smaller than 45, so 13 goes next.45, 13, 62, 6, 33, 28 | 1 | 0 |
| 5 | 13, 45, 62, 6, 33, 28 | 13 moves in front of 45, and the left run moves one place right to make room.13, 45, 62, 6, 33, 28 | 1 | 1 |
| 6 | 13, 45, 62, 6, 33, 28 | One run is used up, so the 1 number left in the other follows as it stands.13, 45, 62, 6, 33, 28 | 1 | 2 |
| 7 | 13, 45, 62, 6, 33, 28 | Merge the run that starts at place 3 with the one that starts at place 4.13, 45, 62, 6, 33, 28 | 1 | 2 |
| 8 | 13, 45, 62, 6, 33, 28 | 6 is smaller than 62, so 6 goes next.13, 45, 62, 6, 33, 28 | 2 | 2 |
| 9 | 13, 45, 6, 62, 33, 28 | 6 moves in front of 62, and the left run moves one place right to make room.13, 45, 6, 62, 33, 28 | 2 | 3 |
| 10 | 13, 45, 6, 62, 33, 28 | One run is used up, so the 1 number left in the other follows as it stands.13, 45, 6, 62, 33, 28 | 2 | 4 |
| 11 | 13, 45, 6, 62, 33, 28 | Merge the run that starts at place 5 with the one that starts at place 6.13, 45, 6, 62, 33, 28 | 2 | 4 |
| 12 | 13, 45, 6, 62, 33, 28 | 28 is smaller than 33, so 28 goes next.13, 45, 6, 62, 33, 28 | 3 | 4 |
| 13 | 13, 45, 6, 62, 28, 33 | 28 moves in front of 33, and the left run moves one place right to make room.13, 45, 6, 62, 28, 33 | 3 | 5 |
| 14 | 13, 45, 6, 62, 28, 33 | One run is used up, so the 1 number left in the other follows as it stands.13, 45, 6, 62, 28, 33 | 3 | 6 |
| 15 | 13, 45, 6, 62, 28, 33 | Merge neighbouring runs of up to 2 numbers into runs of up to 4.13, 45, 6, 62, 28, 33 | 3 | 6 |
| 16 | 13, 45, 6, 62, 28, 33 | Merge the run that starts at place 1 with the one that starts at place 3.13, 45, 6, 62, 28, 33 | 3 | 6 |
| 17 | 13, 45, 6, 62, 28, 33 | 6 is smaller than 13, so 6 goes next.13, 45, 6, 62, 28, 33 | 4 | 6 |
| 18 | 6, 13, 45, 62, 28, 33 | 6 moves in front of 13, and the left run moves one place right to make room.6, 13, 45, 62, 28, 33 | 4 | 7 |
| 19 | 6, 13, 45, 62, 28, 33 | 13 is not bigger than 62, so 13 goes next, where it already stands.6, 13, 45, 62, 28, 33 | 5 | 8 |
| 20 | 6, 13, 45, 62, 28, 33 | 45 is not bigger than 62, so 45 goes next, where it already stands.6, 13, 45, 62, 28, 33 | 6 | 9 |
| 21 | 6, 13, 45, 62, 28, 33 | One run is used up, so the 1 number left in the other follows as it stands.6, 13, 45, 62, 28, 33 | 6 | 10 |
| 22 | 6, 13, 45, 62, 28, 33 | The run that starts at place 5 has no partner this round, so it waits.6, 13, 45, 62, 28, 33 | 6 | 10 |
| 23 | 6, 13, 45, 62, 28, 33 | Merge neighbouring runs of up to 4 numbers into runs of up to 6.6, 13, 45, 62, 28, 33 | 6 | 10 |
| 24 | 6, 13, 45, 62, 28, 33 | Merge the run that starts at place 1 with the one that starts at place 5.6, 13, 45, 62, 28, 33 | 6 | 10 |
| 25 | 6, 13, 45, 62, 28, 33 | 6 is not bigger than 28, so 6 goes next, where it already stands.6, 13, 45, 62, 28, 33 | 7 | 11 |
| 26 | 6, 13, 45, 62, 28, 33 | 13 is not bigger than 28, so 13 goes next, where it already stands.6, 13, 45, 62, 28, 33 | 8 | 12 |
| 27 | 6, 13, 45, 62, 28, 33 | 28 is smaller than 45, so 28 goes next.6, 13, 45, 62, 28, 33 | 9 | 12 |
| 28 | 6, 13, 28, 45, 62, 33 | 28 moves in front of 45, and the left run moves one place right to make room.6, 13, 28, 45, 62, 33 | 9 | 13 |
| 29 | 6, 13, 28, 45, 62, 33 | 33 is smaller than 45, so 33 goes next.6, 13, 28, 45, 62, 33 | 10 | 13 |
| 30 | 6, 13, 28, 33, 45, 62 | 33 moves in front of 45, and the left run moves one place right to make room.6, 13, 28, 33, 45, 62 | 10 | 14 |
| 31 | 6, 13, 28, 33, 45, 62 | One run is used up, so the 2 numbers left in the other follow as they stand.6, 13, 28, 33, 45, 62 | 10 | 16 |
| 32 | 6, 13, 28, 33, 45, 62 | In order, after 10 comparisons, with 16 numbers placed into merged runs.6, 13, 28, 33, 45, 62 | 10 | 16 |
In all, 16 numbers placed. The formula from section 4, , gives at : the same.
where you meet it
Merge sort keeps equal items in order, at the price of a second row.
the C++ library's stable sort
The GNU C++ library's std::stable_sort keeps equal items in order. With room for half the row, it sorts each half bottom up, from groups of 7 sorted by insertion sort, then merges the halves.
source: the GNU C++ library's stl_algo.h in GCC 15, its __stable_sort, __merge_sort_with_buffer and __chunk_insertion_sort, chunk size 7
Timsort, in Python and Java
Python's list sort, and Java's for things other than plain numbers, use Timsort. It is a merge sort that starts from runs already in the row. A row in order is one run.
source: the books' volume one, chapter 10; Python 3.14's list.sort, run for this page; OpenJDK 25's java.util.ComparableTimSort and java.util.TimSort
sorting a file too big for memory
A merge reads each run from front to back, so runs can wait in files on a disk. The GNU sort command sorts big files this way, merging up to 16 at once by default.
source: the GNU coreutils 9.7 manual, the sort command's option batch-size
what is used instead
When room is short and equal items may swap, a sort needing less room is used instead. The GNU C++ library's std::sort is one; it splits like quick sort.
how it compares
Merge sort beside the other sorts, 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.