Bubble sort
how it works
The idea in a few sentences and two pictures, then one row sorted step by step.
Bubble sort puts a row of numbers in order, smallest first. A walk goes along the row from the left, comparing each pair of neighbours. When the left one is bigger, the two swap. So the biggest number met so far is carried right, and one walk takes the biggest of all to the end, where it stays. The next walk stops one place sooner. A small number moves left at most one place a walk, since the walk passes it once. Equal neighbours never swap, so equal numbers keep the order they came in. The sort stops after a walk that swaps nothing.
| the row | 40, 10, 20, 30 |
|---|---|
| after swap 1 | 10, 40, 20, 30 |
| after swap 2 | 10, 20, 40, 30 |
| after swap 3 | 10, 20, 30, 40 |
| the row | 42, 7, 31, 18, 56, 23, 12, 49 |
|---|---|
| after walk 1 | 7, 31, 18, 42, 23, 12, 49, 56 |
| after walk 2 | 7, 18, 31, 23, 12, 42, 49, 56 |
| after walk 3 | 7, 18, 23, 12, 31, 42, 49, 56 |
| after walk 4 | 7, 18, 12, 23, 31, 42, 49, 56 |
| after walk 5 | 7, 12, 18, 23, 31, 42, 49, 56 |
step 2 of 48
42 is bigger than 7, so they are the wrong way round.
what it remembers to know where it is
- walk number
- 1
- pair starting at position
- 1
- swapped on this walk
- no
step 3 of 48
Swap them: 7 moves left and 42 moves right.
what it remembers to know where it is
- walk number
- 1
- pair starting at position
- 1
- swapped on this walk
- yes
step 8 of 48
42 is not bigger than 56, so they stay as they are.
what it remembers to know where it is
- walk number
- 1
- pair starting at position
- 4
- swapped on this walk
- yes
step 15 of 48
56 is now at the end of the unsorted part. Nothing bigger is left, so it stays there for good.
what it remembers to know where it is
- walk number
- 1
- pair starting at position
- not yet
- swapped on this walk
- yes
Where it says not yet, nothing is held there at that moment.
step 25 of 48
49 is now at the end of the unsorted part. Nothing bigger is left, so it stays there for good.
what it remembers to know where it is
- walk number
- 2
- pair starting at position
- not yet
- swapped on this walk
- yes
Where it says not yet, nothing is held there at that moment.
step 47 of 48
That walk swapped nothing, so everything left is already in order.
what it remembers to know where it is
- walk number
- 6
- pair starting at position
- not yet
- swapped on this walk
- no
Where it says not yet, nothing is held there at that moment.
step 48 of 48
In order, after 27 comparisons and 13 swaps.
what it remembers to know where it is
- walk number
- 6
- pair starting at position
- not yet
- swapped on this walk
- no
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
- repeat a walkPython lines 11 and 12
- along the unsorted part, one neighbouring pair at a timePython line 13
- if the left one is bigger than the right onePython line 14
- swap themPython lines 15 and 16
- the end of the unsorted part is now in placePython line 19
- until a walk swaps nothingPython lines 17 and 18
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 bubble_sort(numbers):
"""Put a list of numbers in order, smallest first, in the list itself.
Walk along the list comparing each pair of neighbours, and swap any pair
standing the wrong way round. Each walk carries the biggest number left to
the end, so the next walk can stop one place sooner. A walk that swaps
nothing means the list is in order. The list is sorted where it stands,
with no copy made, and handed back.
"""
end = len(numbers) - 1 # the last place the unsorted part reaches
while end > 0:
swapped = False
for i in range(end): # i runs through 0, 1, and so on up to end - 1
if numbers[i] > numbers[i + 1]:
numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i] # both at once
swapped = True
if not swapped:
break # nothing moved, so everything left is in order
end -= 1 # the biggest number left is now in its place
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 back to front climbs two steps up for each step across: ten times the numbers, a hundred times the comparisons. Section 4 shows why. A row in order climbs one step up for each step across. A shuffled row climbs like a row back to front, a little lower; its points are the mean of 20 shuffles at each length, not of every order.
comparisons, ten times more at each mark up
, how many numbers are in the row, ten times more at each mark to the right
- back to front, 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, different numbers in a random order, every order as likelypoints only, each measured by a real run, since no single formula for the comparisons of this row is worked out here
- already in order, the cheapest rowsolid 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 bubble 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 already in order, on a row back to front, 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 __gt__(self, other):
Counted.comparisons += 1
return self.value > other.value
def bubble_sort(numbers):
"""Put a list of numbers in order, smallest first, in the list itself.
Walk along the list comparing each pair of neighbours, and swap any pair
standing the wrong way round. Each walk carries the biggest number left to
the end, so the next walk can stop one place sooner. A walk that swaps
nothing means the list is in order. The list is sorted where it stands,
with no copy made, and handed back.
"""
end = len(numbers) - 1 # the last place the unsorted part reaches
while end > 0:
swapped = False
for i in range(end): # i runs through 0, 1, and so on up to end - 1
if numbers[i] > numbers[i + 1]:
numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i] # both at once
swapped = True
if not swapped:
break # nothing moved, so everything left is in order
end -= 1 # the biggest number left is now in its place
return numbers
def count(row):
"""How many comparisons bubble sort makes on this row."""
Counted.comparisons = 0
bubble_sort([Counted(x) for x in row])
return Counted.comparisons
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>6} {'in order':>10} {'back to front':>14} {'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)))
back_to_front = count(list(range(n, 0, -1)))
print(f"{n:>6} {in_order:>10} {back_to_front:>14} {sum(shuffles) / 20:>10.1f}")
best, worst and average
The same walks 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.
| bestalready in order, the cheapest row | averageshuffled, different numbers in a random order, every order as likely | worstback to front, one of the dearest rows | |
|---|---|---|---|
| comparisons | between and | ||
| swaps | none | ||
| how the comparisons grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: 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
Extra memory is the room it needs on top of the input itself, while it runs.
| row of 5 | comparisons | swaps |
|---|---|---|
| 1, 2, 3, 4, 5 | 4 | 0 |
| all 120 orders, on average | about 9.26 | 5 |
| 5, 4, 3, 2, 1 | 10 | 10 |
where the formula comes from
Each count above, worked out in small steps.
the move: count what walk k looks at
the line:why it is allowed: Each walk leaves the biggest number of its part at the end, so the part loses one number a walk. For walk 2 of 5 numbers, the first 4.
the move: open the bracket
the line:why it is allowed: Taking away is taking away and adding 1. For walk 2 of 5, 5 less 2, plus 1, is 4.
guess it, thenthe move: count the pairs among them
the line:why it is allowed: Neighbouring pairs are one fewer than the numbers. 4 numbers make 3 pairs.
guess it, thenthe move: count the walks
the line:why it is allowed: Put for in line 2. For 5 numbers, walk 4 looks at 5 less 4, plus 1, so 2 numbers. After it one number is left, with no pair. The sort may stop sooner, after a walk that swaps nothing.
guess it, thenthe move: no row costs more
the line:why it is allowed: Any row runs walk 1, walk 2 and on, at most walks by line 4, and walk compares pairs by line 3. For 4 numbers, at most 3 + 2 + 1.
guess it, thenthe move: see why this row never stops early
the line:the row 5, 4, 3, 2, 1 after walk 1 4, 3, 2, 1, 5 after walk 2 3, 2, 1, 4, 5 after walk 3 2, 1, 3, 4, 5 after walk 4 1, 2, 3, 4, 5 Each walk carries the biggest number left to the end. The rest stay back to front, one number shorter. why it is allowed: Back to front, every pair of neighbours is wrong. Walk 1 carries the biggest number to the end. Each swap passes it over one other number, so the rest keep their order: 5, 4, 3 becomes 4, 5, 3, the 4 still before the 3. They stay back to front, so every walk starts with a wrong pair and swaps, and all walks run.
guess it, thenthe move: add up the walks
the line:why it is allowed: is the comparisons on a row back to front. By line 6 every walk runs, and by line 3 they make , then one fewer, down to 1. For 5 numbers, 4 + 3 + 2 + 1.
guess it, thenthe move: so this row is one of the dearest
the line:why it is allowed: By line 5 no row costs more, and by line 7 this row costs just that.
guess it, thenthe move: write the same sum backwards
the line:why it is allowed: The same numbers in the other order. For 5 numbers, 1 + 2 + 3 + 4.
guess it, thenthe move: add the two lines, column by column
the line:For a row of 5, line 9's 1, 2, 3, 4 in yellow and line 7's 4, 3, 2, 1 in blue. Each column is 5 tall, so together they fill a rectangle 4 wide and 5 tall, twice the sum. why it is allowed: Lay line 9 under line 7. Column holds and , which make .
guess it, thenthe move: count the columns
the line:why it is allowed: One column for each walk, columns of . For 5 numbers, 4 columns of 5, which is 20.
guess it, thenthe move: halve both sides
the line:why it is allowed: For 5 numbers, half of 20 is 10, the 4 + 3 + 2 + 1 of line 7.
guess it, thenthe move: multiply out the bracket
the line:why it is allowed: lots of make , and lots of 1 make .
guess it, thenthe move: halve each part
the line:why it is allowed: Half of a difference is the difference of the halves.
guess it, thenthe move: see what a long row costs
the line:why it is allowed: Line 14 takes from . For 2,000 numbers, 1,000 from 2,000,000.
guess it, thenthe move: square ten times the numbers
the line:why it is allowed: times , and 10 times 10 is 100.
guess it, thenthe move: ten times the numbers
the line:why it is allowed: Put for in line 15, and line 16 makes its square 100 times bigger. 1,000 numbers cost 499,500 comparisons and 10,000 cost 49,995,000, about 100 times. On section 2's plot that is one step across and two steps up.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 14 takes something away from .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 18, stays under half of , however long the row.
guess it, thenthe move: a fact for the floor
the line:why it is allowed: Line 14 takes away. For a floor, must stay above a fixed share of , so swap that for , at least as big. Any share under a half would do; a quarter leaves a quarter. Times 4, this line says twice is at most times , true once is 2 or more. For 10 numbers, 5 is at most 25.
guess it, thenthe move: a floor
the line:why it is allowed: Swap line 14's for line 20's , at least as big; taking that away leaves no more. For 10 numbers, 45 is at least 50 less 25.
guess it, thenthe move: tidy the floor
the line:why it is allowed: Half less a quarter is a quarter.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 22, never drops below a quarter of from 2 numbers on. A floor need only hold for rows long enough; at 1 number is 0.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 23 and 19 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: no row costs less
the line:why it is allowed: The first walk runs over the whole row, so it compares all its pairs. For 5 numbers, 4.
the move: walk once
the line:walk 1 compares they swap 1 and 2 no 2 and 3 no 3 and 4 no 4 and 5 no On 1, 2, 3, 4, 5, walk 1 compares its 4 pairs and swaps none, so the sort stops after 4 comparisons, which is 5 less 1. why it is allowed: is now the comparisons on a row in order. No pair is wrong, so the first walk swaps nothing and ends the sort.
guess it, thenthe move: so this row is a cheapest one
the line:why it is allowed: By line 1 no row costs less, and by line 2 this row costs just that.
guess it, thenthe move: a ceiling
the line:why it is allowed: Taking 1 from leaves less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 4.
guess it, thenthe move: a ceiling, true but loose
the line:why it is allowed: By line 4, and is at most times from 1 number on.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6. True, but loose; line 5 is a far lower ceiling.
guess it, thenthe move: a fact for the floor
the line:why it is allowed: Half of is at least 1 once is 2 or more.
guess it, thenthe move: a floor
the line:why it is allowed: Swap line 2's 1 for line 8's , at least as big; taking that away leaves no more. For 10 numbers, 9 is at least 10 less 5.
guess it, thenthe move: tidy the floor
the line:why it is allowed: less half of is half of .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 10, from 2 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 11 and 5 bound by the same growth, .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: count the pairs
the line:why it is allowed: Here a pair is any two numbers, neighbours or not. The first pairs with the after it, the next with one fewer, down to the last two. For 4 numbers, 3 + 2 + 1.
the move: the first ladder's sum
the line:why it is allowed: The first ladder adds up this sum, in its line 12. For 4 numbers, 6 pairs.
guess it, thenthe move: see what one swap changes
the line:why it is allowed: Nothing stands between two neighbours, so every other number stays before both or after both. Swapping 8 and 5 in 3, 8, 5, 1 gives 3, 5, 8, 1, and only that pair has turned. The 8 is still before the 1.
guess it, thenthe move: name the wrong pairs
the line:why it is allowed: 3, 8, 5, 1 has four inversions, 3 and 1, 8 and 5, 8 and 1, 5 and 1.
guess it, thenthe move: see what each swap does to them
the line:after row inversions the start 3, 8, 5, 1 4 swap 1 3, 5, 8, 1 3 swap 2 3, 5, 1, 8 2 swap 3 3, 1, 5, 8 1 swap 4 1, 3, 5, 8 0 Bubble sort on 3, 8, 5, 1. Each swap mends one inversion, so 4 inversions take 4 swaps. why it is allowed: Bubble sort swaps only a wrong pair of neighbours, so the swap mends it. By line 3 it changes no other pair.
guess it, thenthe move: count the swaps as inversions
the line:why it is allowed: At the end no inversion is left. By line 5 each swap mended exactly one.
guess it, thenthe move: say what the average is
the line:why it is allowed: is the swaps averaged over every shuffle of different numbers: add them up, then divide by how many shuffles there are. The 6 shuffles of 1, 2, 3 have 0, 1, 1, 2, 2 and 3 inversions, 9 in all, so 1.5 on average.
guess it, thenthe move: count the same total pair by pair
the line:shuffle 1 and 2 1 and 3 2 and 3 total 1, 2, 3 0 1, 3, 2 wrong 1 2, 1, 3 wrong 1 2, 3, 1 wrong wrong 2 3, 1, 2 wrong wrong 2 3, 2, 1 wrong wrong wrong 3 times wrong 3 3 3 9 The 6 shuffles of 1, 2 and 3, each pair marked wrong where its bigger number comes first. why it is allowed: Count the marks in the grid by rows, 0, 1, 1, 2, 2, 3, or by columns, 3, 3, 3. Both make 9.
guess it, thenthe move: divide by the shuffles
the line:why it is allowed: A pair's share is the part of the shuffles it is wrong in. In the grid, 9 / 6 = 3/6 + 3/6 + 3/6 = 1.5.
guess it, thenthe move: half the time each
the line:pair 1 and 2 wrong trade the 1 and the 2: right 2, 1, 3 1, 2, 3 2, 3, 1 1, 3, 2 3, 2, 1 3, 1, 2 Trading the 1 and the 2 matches each shuffle where that pair is wrong with one where it is right. why it is allowed: Trading the places of the 1 and the 2 turns each shuffle with that pair wrong into one with it right, and back. So it is wrong in exactly half. The same holds for any pair and any .
guess it, thenthe move: add up the halves
the line:why it is allowed: By line 9, adds up every pair's share. By line 10 each share is a half, and by line 2 there are that many pairs.
guess it, thenthe move: multiply the fractions
the line:why it is allowed: Half of a half is a quarter. For 3 numbers, 3 times 2 over 4 is 1.5, as in the grid.
guess it, thenthe move: multiply out the bracket
the line:why it is allowed: lots of make , and lots of 1 make .
guess it, thenthe move: take a quarter of each part
the line:why it is allowed: A quarter of a difference is the difference of the quarters.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 14 takes something away from .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 15, stays under a quarter of .
guess it, thenthe move: a fact for the floor
the line:why it is allowed: Times 8, this says twice is at most times , true once is 2 or more, as at the first ladder's line 20.
guess it, thenthe move: a floor
the line:why it is allowed: Swap line 14's for line 17's , at least as big; taking that away leaves no more. For 10 numbers, 22.5 is at least 25 less 12.5.
guess it, thenthe move: tidy the floor
the line:why it is allowed: A quarter less an eighth is an eighth.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 19, from 2 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 20 and 16 bound by the same growth, .
guess it, then
try it on small rows: over every order of 4 numbers, the average is
the move: a floor from the swaps
the line:why it is allowed: is the comparisons averaged over every shuffle. Every swap follows a comparison, so is at least the average swaps, line 12 of the ladder before.
the move: a simpler floor
the line:why it is allowed: The ladder before shows that is at least from 2 numbers on, in its lines 12 to 19.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 2.
guess it, thenthe move: a ceiling from the dearest rows
the line:numbers line 1 the average line 4 3 1.5 about 2.83 3 5 5 about 9.26 10 8 14 about 26 28 The comparisons averaged over every order of 3, 5 and 8 different numbers, counted on this site's bubble sort. why it is allowed: By the first ladder's lines 5 and 12, no row costs more than this, so neither does the average. The picture shows the real averages between lines 1 and 4, nearer the ceiling.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: The first ladder's line 14 writes line 4 as half of less half of , and its line 18 says that is at most half of .
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, .
guess it, then
try it on small rows: over every order of 4 numbers, the average is about 5.58
the move: every pair is wrong
the line:why it is allowed: In 5, 4, 3, 2, 1 the 2 is smaller than the 3, and the 3 than the 4, so the 2 is smaller than the 4 too. Order carries along, so each number is smaller than every number before it.
the move: one swap for each
the line:why it is allowed: is the swaps on this row. By the third ladder's line 6 they are its inversions, and by that ladder's line 2 a row has this many pairs. By this ladder's line 1 all are inversions. For 5 numbers, 10.
guess it, thenthe move: no row takes more
the line:why it is allowed: A row's swaps are its inversions, and it has no more inversions than pairs.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
count it yourself
Count every step on four numbers back to front, then check the comparisons against . 4 times 3 over 2 is 6.
| step | the row | what happens | comparisons | swaps |
|---|---|---|---|---|
| 1 | 4, 3, 2, 1 | There are 4 numbers in a row. Walk along it from the left, comparing each neighbouring pair.4, 3, 2, 1 | 0 | 0 |
| 2 | 4, 3, 2, 1 | 4 is bigger than 3, so they are the wrong way round.4, 3, 2, 1 | 1 | 0 |
| 3 | 3, 4, 2, 1 | Swap them: 3 moves left and 4 moves right.3, 4, 2, 1 | 1 | 1 |
| 4 | 3, 4, 2, 1 | 4 is bigger than 2, so they are the wrong way round.3, 4, 2, 1 | 2 | 1 |
| 5 | 3, 2, 4, 1 | Swap them: 2 moves left and 4 moves right.3, 2, 4, 1 | 2 | 2 |
| 6 | 3, 2, 4, 1 | 4 is bigger than 1, so they are the wrong way round.3, 2, 4, 1 | 3 | 2 |
| 7 | 3, 2, 1, 4 | Swap them: 1 moves left and 4 moves right.3, 2, 1, 4 | 3 | 3 |
| 8 | 3, 2, 1, 4 | 4 is now at the end of the unsorted part. Nothing bigger is left, so it stays there for good.3, 2, 1, 4 | 3 | 3 |
| 9 | 3, 2, 1, 4 | 3 is bigger than 2, so they are the wrong way round.3, 2, 1, 4 | 4 | 3 |
| 10 | 2, 3, 1, 4 | Swap them: 2 moves left and 3 moves right.2, 3, 1, 4 | 4 | 4 |
| 11 | 2, 3, 1, 4 | 3 is bigger than 1, so they are the wrong way round.2, 3, 1, 4 | 5 | 4 |
| 12 | 2, 1, 3, 4 | Swap them: 1 moves left and 3 moves right.2, 1, 3, 4 | 5 | 5 |
| 13 | 2, 1, 3, 4 | 3 is now at the end of the unsorted part. Nothing bigger is left, so it stays there for good.2, 1, 3, 4 | 5 | 5 |
| 14 | 2, 1, 3, 4 | 2 is bigger than 1, so they are the wrong way round.2, 1, 3, 4 | 6 | 5 |
| 15 | 1, 2, 3, 4 | Swap them: 1 moves left and 2 moves right.1, 2, 3, 4 | 6 | 6 |
| 16 | 1, 2, 3, 4 | 2 is now at the end of the unsorted part. Nothing bigger is left, so it stays there for good.1, 2, 3, 4 | 6 | 6 |
| 17 | 1, 2, 3, 4 | Only 1 is left, so it is in place too.1, 2, 3, 4 | 6 | 6 |
| 18 | 1, 2, 3, 4 | In order, after 6 comparisons and 6 swaps.1, 2, 3, 4 | 6 | 6 |
In all, 6 comparisons. The formula from section 4, , gives at : the same.
where you meet it
Bubble sort is mostly met as a lesson. Here is where it, or a close relative, does real work.
checking that a row is in order
One walk that swaps nothing shows the row is in order, after comparisons, since order carries along. A program checks a row it is handed the same way.
source: Algorithmic Thinking Without the Jargon, volume one, chapter 8; cppreference, a reference for the C++ language written by its users, on std::is_sorted, its check that a row is in order
sorting on many small processors at once
Some machines give each number its own small processor, so many pairs of neighbours can be compared at the same moment. Odd-even transposition sort works in rounds. A transposition is a swap, and like bubble sort it swaps only wrong neighbours. One round takes places 1 and 2, 3 and 4, and on; the next, places 2 and 3, 4 and 5, and on. On 4, 3, 2, 1, round 1 gives 3, 4, 1, 2 and round 2 gives 3, 1, 4, 2. Round 3 gives 1, 3, 2, 4 and round 4 gives 1, 2, 3, 4. Each round takes the time of one comparison, so 4 rounds, where bubble sort makes 6 comparisons one after another.
source: Donald Knuth, The Art of Computer Programming, volume 3
in a first course on sorting
Bubble sort is a fixture of first lessons and textbooks. Owen Astrachan followed it back through early surveys and books. In his timings insertion sort ran close to three times faster. He finds little in its favour today, and suggests its place in teaching came from early textbooks, the small memories of early machines, and history.
source: Owen Astrachan, Bubble sort, an archaeological algorithmic analysis, at SIGCSE 2003, a conference on teaching computing
what is used instead
The ready-made sorts of Python, Java and C++ contain no bubble sort, as Sebastian Bourges' books, Algorithmic Thinking Without the Jargon, note in volume one, chapter 8. Python's sorted uses Timsort, and so does Java when it sorts things other than plain numbers, such as words. Timsort finds stretches already in order and merges them, joining two ordered stretches into one: 1, 4 and 2, 3 make 1, 2, 3, 4. C++'s std::sort is usually introsort, a mix of quicker methods. All three hand short stretches to a form of insertion sort, as short to write as bubble sort. It takes each number in turn and slides it left past the bigger numbers before it. On 2, 4, 6, 8, 1 it compares the 4, the 6 and the 8 once each with the number before. Then it slides the 1 past all four: 3 + 4 = 7 comparisons, where bubble sort makes 10. So a new number at the end of a list in order costs it about the list's length when biggest, and about twice that when smallest. For 1,000 numbers that is 999 and 1,997.
how it compares
Bubble 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.