Skip to content

Bubble sort

ordering

Level 1 of 3

Also called Sinking 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 row40, 10, 20, 30
after swap 110, 40, 20, 30
after swap 210, 20, 40, 30
after swap 310, 20, 30, 40
One walk on 40, 10, 20, 30. The 40 is bigger than each number after it, so it swaps three times and ends last. A second walk swaps nothing, so the sort stops.
the row42, 7, 31, 18, 56, 23, 12, 49
after walk 17, 31, 18, 42, 23, 12, 49, 56
after walk 27, 18, 31, 23, 12, 42, 49, 56
after walk 37, 18, 23, 12, 31, 42, 49, 56
after walk 47, 18, 12, 23, 31, 42, 49, 56
after walk 57, 12, 18, 23, 31, 42, 49, 56
The same row as the step-by-step run below, after each walk. 8 numbers make 7 pairs, and each walk compares one fewer. Walk 1 carries the 42 up to the 56, then the 56 to the end. The 12 moves one place left a walk. Walk 6 swaps nothing, so 7 + 6 + 5 + 4 + 3 + 2 = 27 comparisons.
A short shuffle: 7 moments of its 48 steps, the steps between them left for the watch page
  1. step 2 of 48

    427311856231249

    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

    watch from here

  2. step 3 of 48

    742311856231249

    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

    watch from here

  3. step 8 of 48

    731184256231249

    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

    watch from here

  4. step 15 of 48

    731184223124956

    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.

    watch from here

  5. step 25 of 48

    718312312424956

    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.

    watch from here

  6. step 47 of 48

    712182331424956

    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.

    watch from here

  7. step 48 of 48

    712182331424956

    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.

    watch from here

the steps, in plain words
  1. repeat a walkPython lines 11 and 12
  2. along the unsorted part, one neighbouring pair at a timePython line 13
  3. if the left one is bigger than the right onePython line 14
  4. swap themPython lines 15 and 16
  5. the end of the unsorted part is now in placePython line 19
  6. 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

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

nn, 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
what a dearest row costs, at a billion comparisons a second
nncomparisonstime
1,000499,500about 500 microseconds
100,0004,999,950,000about 5 seconds
10,000,00049,999,995,000,000about 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestalready in order, the cheapest rowaverageshuffled, different numbers in a random order, every order as likelyworstback to front, one of the dearest rows
comparisonsn−1n - 1between n(n−1)4\frac{n(n - 1)}{4} and n(n−1)2\frac{n(n - 1)}{2}n(n−1)2\frac{n(n - 1)}{2}
swapsnonen(n−1)4\frac{n(n - 1)}{4}n(n−1)2\frac{n(n - 1)}{2}
how the comparisons grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)
ceiling, OOO(n)O(n)O(n2)O(n^2)O(n2)O(n^2)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n2)\Omega(n^2)Ω(n2)\Omega(n^2)

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 5comparisonsswaps
1, 2, 3, 4, 540
all 120 orders, on averageabout 9.265
5, 4, 3, 2, 11010
In order, one walk of 4 comparisons and no swap. Back to front, 4 + 3 + 2 + 1 = 10 of each, and 5 times 4 over 2 is 10. 5 numbers stand in 5 × 4 × 3 × 2 × 1 = 120 orders, 5 choices for the first place, 4 for the next, and on. On average, 5 swaps, which is 5 times 4 over 4, and about 9.26 comparisons, counted over all 120, between 5 and 10.

where the formula comes from

Each count above, worked out in small steps.

Why does a row back to front cost n(n−1)2\frac{n(n - 1)}{2} comparisons, the most any row can?
  1. the move: count what walk k looks at

    the line:
    after k−1 walks, walk k looksat the first n−(k−1) numbers\begin{gathered} \text{after } k - 1 \text{ walks, walk } k \text{ looks} \\ \text{at the first } n - (k - 1) \text{ numbers} \end{gathered}

    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.

  2. the move: open the bracket

    the line:
    that is the firstn−k+1 numbers\begin{gathered} \text{that is the first} \\ n - k + 1 \text{ numbers} \end{gathered}

    why it is allowed: Taking away k−1k - 1 is taking away kk and adding 1. For walk 2 of 5, 5 less 2, plus 1, is 4.

  3. the move: count the pairs among them

    the line:
    so walk k compares n−k pairs\text{so walk } k \text{ compares } n - k \text{ pairs}

    why it is allowed: Neighbouring pairs are one fewer than the numbers. 4 numbers make 3 pairs.

  4. the move: count the walks

    the line:
    there are at most n−1 walks\text{there are at most } n - 1 \text{ walks}

    why it is allowed: Put n−1n - 1 for kk 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.

  5. the move: no row costs more

    the line:
    no row of n numberscosts more than(n−1)+⋯+1\begin{gathered} \text{no row of } n \text{ numbers} \\ \text{costs more than} \\ (n - 1) + \dots + 1 \end{gathered}

    why it is allowed: Any row runs walk 1, walk 2 and on, at most n−1n - 1 walks by line 4, and walk kk compares n−kn - k pairs by line 3. For 4 numbers, at most 3 + 2 + 1.

  6. the move: see why this row never stops early

    the line:
    on a row back to front,every walk swaps\begin{gathered} \text{on a row back to front,} \\ \text{every walk swaps} \end{gathered}
    the row5, 4, 3, 2, 1
    after walk 14, 3, 2, 1, 5
    after walk 23, 2, 1, 4, 5
    after walk 32, 1, 3, 4, 5
    after walk 41, 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 n−1n - 1 walks run.

  7. the move: add up the walks

    the line:
    C=(n−1)+⋯+1C = (n - 1) + \dots + 1

    why it is allowed: CC is the comparisons on a row back to front. By line 6 every walk runs, and by line 3 they make n−1n - 1, then one fewer, down to 1. For 5 numbers, 4 + 3 + 2 + 1.

  8. the move: so this row is one of the dearest

    the line:
    a row back to front isone of the dearest\begin{gathered} \text{a row back to front is} \\ \text{one of the dearest} \end{gathered}

    why it is allowed: By line 5 no row costs more, and by line 7 this row costs just that.

  9. the move: write the same sum backwards

    the line:
    C=1+⋯+(n−1)C = 1 + \dots + (n - 1)

    why it is allowed: The same numbers in the other order. For 5 numbers, 1 + 2 + 3 + 4.

  10. the move: add the two lines, column by column

    the line:
    2C=n+⋯+n2C = n + \dots + n
    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 kk holds n−kn - k and kk, which make nn.

  11. the move: count the columns

    the line:
    2C=n(n−1)2C = n(n - 1)

    why it is allowed: One column for each walk, n−1n - 1 columns of nn. For 5 numbers, 4 columns of 5, which is 20.

  12. the move: halve both sides

    the line:
    C=n(n−1)2C = \frac{n(n - 1)}{2}

    why it is allowed: For 5 numbers, half of 20 is 10, the 4 + 3 + 2 + 1 of line 7.

  13. the move: multiply out the bracket

    the line:
    C=n2−n2C = \frac{n^2 - n}{2}

    why it is allowed: nn lots of nn make n2n^2, and nn lots of 1 make nn.

  14. the move: halve each part

    the line:
    C=n22−n2C = \frac{n^2}{2} - \frac{n}{2}

    why it is allowed: Half of a difference is the difference of the halves.

  15. the move: see what a long row costs

    the line:
    for a long row, C is close to n22\text{for a long row, } C \text{ is close to } \frac{n^2}{2}

    why it is allowed: Line 14 takes n2\frac{n}{2} from n22\frac{n^2}{2}. For 2,000 numbers, 1,000 from 2,000,000.

  16. the move: square ten times the numbers

    the line:
    (10n)2=100 n2(10n)^2 = 100\,n^2

    why it is allowed: 10n10n times 10n10n, and 10 times 10 is 100.

  17. the move: ten times the numbers

    the line:
    ten times the numberscost about 100 timesthe comparisons\begin{gathered} \text{ten times the numbers} \\ \text{cost about 100 times} \\ \text{the comparisons} \end{gathered}

    why it is allowed: Put 10n10n for nn 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.

  18. the move: a ceiling

    the line:
    C≤n22C \le \frac{n^2}{2}

    why it is allowed: Line 14 takes something away from n22\frac{n^2}{2}.

  19. the move: read it as a bound

    the line:
    C∈O(n2)C \in O(n^2)

    why it is allowed: By line 18, CC stays under half of n2n^2, however long the row.

  20. the move: a fact for the floor

    the line:
    n2≤n24 for n≥2\frac{n}{2} \le \frac{n^2}{4} \text{ for } n \ge 2

    why it is allowed: Line 14 takes n2\frac{n}{2} away. For a floor, CC must stay above a fixed share of n2n^2, so swap that n2\frac{n}{2} for n24\frac{n^2}{4}, at least as big. Any share under a half would do; a quarter leaves a quarter. Times 4, this line says twice nn is at most nn times nn, true once nn is 2 or more. For 10 numbers, 5 is at most 25.

  21. the move: a floor

    the line:
    C≥n22−n24 for n≥2C \ge \frac{n^2}{2} - \frac{n^2}{4} \text{ for } n \ge 2

    why it is allowed: Swap line 14's n2\frac{n}{2} for line 20's n24\frac{n^2}{4}, at least as big; taking that away leaves no more. For 10 numbers, 45 is at least 50 less 25.

  22. the move: tidy the floor

    the line:
    C≥n24 for n≥2C \ge \frac{n^2}{4} \text{ for } n \ge 2

    why it is allowed: Half less a quarter is a quarter.

  23. the move: read it as a bound

    the line:
    C∈Ω(n2)C \in \Omega(n^2)

    why it is allowed: By line 22, CC never drops below a quarter of n2n^2 from 2 numbers on. A floor need only hold for rows long enough; at 1 number CC is 0.

  24. the move: a ceiling and a floor together

    the line:
    C∈Θ(n2)C \in \Theta(n^2)

    why it is allowed: Lines 23 and 19 bound CC by the same growth, n2n^2.

try it with a small nn: at n=4n = 4, line 7 gives C=6C = 6, which you can work out by hand

Why does a row in order cost only n−1n - 1 comparisons, the fewest any row can?
  1. the move: no row costs less

    the line:
    no row costs fewer than n−1\text{no row costs fewer than } n - 1

    why it is allowed: The first walk runs over the whole row, so it compares all its pairs. For 5 numbers, 4.

  2. the move: walk once

    the line:
    C=n−1C = n - 1
    walk 1 comparesthey swap
    1 and 2no
    2 and 3no
    3 and 4no
    4 and 5no
    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: CC is now the comparisons on a row in order. No pair is wrong, so the first walk swaps nothing and ends the sort.

  3. the move: so this row is a cheapest one

    the line:
    a row already in orderis a cheapest row\begin{gathered} \text{a row already in order} \\ \text{is a cheapest row} \end{gathered}

    why it is allowed: By line 1 no row costs less, and by line 2 this row costs just that.

  4. the move: a ceiling

    the line:
    C≤nC \le n

    why it is allowed: Taking 1 from nn leaves less than nn.

  5. the move: read it as a bound

    the line:
    C∈O(n)C \in O(n)

    why it is allowed: By line 4.

  6. the move: a ceiling, true but loose

    the line:
    C≤n2C \le n^2

    why it is allowed: By line 4, and nn is at most nn times nn from 1 number on.

  7. the move: read it as a bound

    the line:
    C∈O(n2)C \in O(n^2)

    why it is allowed: By line 6. True, but loose; line 5 is a far lower ceiling.

  8. the move: a fact for the floor

    the line:
    1≤n2 for n≥21 \le \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Half of nn is at least 1 once nn is 2 or more.

  9. the move: a floor

    the line:
    C≥n−n2 for n≥2C \ge n - \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Swap line 2's 1 for line 8's n2\frac{n}{2}, at least as big; taking that away leaves no more. For 10 numbers, 9 is at least 10 less 5.

  10. the move: tidy the floor

    the line:
    C≥n2 for n≥2C \ge \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: nn less half of nn is half of nn.

  11. the move: read it as a bound

    the line:
    C∈Ω(n)C \in \Omega(n)

    why it is allowed: By line 10, from 2 numbers on.

  12. the move: a ceiling and a floor together

    the line:
    C∈Θ(n)C \in \Theta(n)

    why it is allowed: Lines 11 and 5 bound CC by the same growth, nn.

try it with a small nn: at n=4n = 4, line 2 gives C=3C = 3, which you can work out by hand

How many swaps does a shuffle take, on average?
  1. the move: count the pairs

    the line:
    a row of n numbers holds(n−1)+⋯+1 pairs\begin{gathered} \text{a row of } n \text{ numbers holds} \\ (n - 1) + \dots + 1 \text{ pairs} \end{gathered}

    why it is allowed: Here a pair is any two numbers, neighbours or not. The first pairs with the n−1n - 1 after it, the next with one fewer, down to the last two. For 4 numbers, 3 + 2 + 1.

  2. the move: the first ladder's sum

    the line:
    that is n(n−1)2 pairs\begin{gathered} \text{that is } \frac{n(n - 1)}{2} \text{ pairs} \end{gathered}

    why it is allowed: The first ladder adds up this sum, in its line 12. For 4 numbers, 6 pairs.

  3. the move: see what one swap changes

    the line:
    a swap of neighbours changesthe order of that pair alone\begin{gathered} \text{a swap of neighbours changes} \\ \text{the order of that pair alone} \end{gathered}

    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.

  4. the move: name the wrong pairs

    the line:
    a pair with the biggernumber first is an inversion\begin{gathered} \text{a pair with the bigger} \\ \text{number first is an inversion} \end{gathered}

    why it is allowed: 3, 8, 5, 1 has four inversions, 3 and 1, 8 and 5, 8 and 1, 5 and 1.

  5. the move: see what each swap does to them

    the line:
    every swap mends one inversionand makes no new one\begin{gathered} \text{every swap mends one inversion} \\ \text{and makes no new one} \end{gathered}
    afterrowinversions
    the start3, 8, 5, 14
    swap 13, 5, 8, 13
    swap 23, 5, 1, 82
    swap 33, 1, 5, 81
    swap 41, 3, 5, 80
    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.

  6. the move: count the swaps as inversions

    the line:
    the swaps are exactly theinversions the row starts with\begin{gathered} \text{the swaps are exactly the} \\ \text{inversions the row starts with} \end{gathered}

    why it is allowed: At the end no inversion is left. By line 5 each swap mended exactly one.

  7. the move: say what the average is

    the line:
    an average over every shuffle,each as likely as the others\begin{gathered} \text{an average over every shuffle,} \\ \text{each as likely as the others} \end{gathered}

    why it is allowed: SS is the swaps averaged over every shuffle of nn 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.

  8. the move: count the same total pair by pair

    the line:
    add the grid by columns,not rows: the same total\begin{gathered} \text{add the grid by columns,} \\ \text{not rows: the same total} \end{gathered}
    shuffle1 and 21 and 32 and 3total
    1, 2, 30
    1, 3, 2wrong1
    2, 1, 3wrong1
    2, 3, 1wrongwrong2
    3, 1, 2wrongwrong2
    3, 2, 1wrongwrongwrong3
    times wrong3339
    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.

  9. the move: divide by the shuffles

    the line:
    so the average adds up eachpair’s share of the shuffles\begin{gathered} \text{so the average adds up each} \\ \text{pair's share of the shuffles} \end{gathered}

    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.

  10. the move: half the time each

    the line:
    each pair stands wrong inexactly half of the shuffles\begin{gathered} \text{each pair stands wrong in} \\ \text{exactly half of the shuffles} \end{gathered}
    pair 1 and 2 wrongtrade the 1 and the 2: right
    2, 1, 31, 2, 3
    2, 3, 11, 3, 2
    3, 2, 13, 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 nn.

  11. the move: add up the halves

    the line:
    S=n(n−1)2×12S = \frac{n(n - 1)}{2} \times \frac{1}{2}

    why it is allowed: By line 9, SS adds up every pair's share. By line 10 each share is a half, and by line 2 there are that many pairs.

  12. the move: multiply the fractions

    the line:
    S=n(n−1)4S = \frac{n(n - 1)}{4}

    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.

  13. the move: multiply out the bracket

    the line:
    S=n2−n4S = \frac{n^2 - n}{4}

    why it is allowed: nn lots of nn make n2n^2, and nn lots of 1 make nn.

  14. the move: take a quarter of each part

    the line:
    S=n24−n4S = \frac{n^2}{4} - \frac{n}{4}

    why it is allowed: A quarter of a difference is the difference of the quarters.

  15. the move: a ceiling

    the line:
    S≤n24S \le \frac{n^2}{4}

    why it is allowed: Line 14 takes something away from n24\frac{n^2}{4}.

  16. the move: read it as a bound

    the line:
    S∈O(n2)S \in O(n^2)

    why it is allowed: By line 15, SS stays under a quarter of n2n^2.

  17. the move: a fact for the floor

    the line:
    n4≤n28 for n≥2\frac{n}{4} \le \frac{n^2}{8} \text{ for } n \ge 2

    why it is allowed: Times 8, this says twice nn is at most nn times nn, true once nn is 2 or more, as at the first ladder's line 20.

  18. the move: a floor

    the line:
    S≥n24−n28 for n≥2S \ge \frac{n^2}{4} - \frac{n^2}{8} \text{ for } n \ge 2

    why it is allowed: Swap line 14's n4\frac{n}{4} for line 17's n28\frac{n^2}{8}, at least as big; taking that away leaves no more. For 10 numbers, 22.5 is at least 25 less 12.5.

  19. the move: tidy the floor

    the line:
    S≥n28 for n≥2S \ge \frac{n^2}{8} \text{ for } n \ge 2

    why it is allowed: A quarter less an eighth is an eighth.

  20. the move: read it as a bound

    the line:
    S∈Ω(n2)S \in \Omega(n^2)

    why it is allowed: By line 19, from 2 numbers on.

  21. the move: a ceiling and a floor together

    the line:
    S∈Θ(n2)S \in \Theta(n^2)

    why it is allowed: Lines 20 and 16 bound SS by the same growth, n2n^2.

try it on small rows: over every order of 4 numbers, the average is S=3S = 3

Between which floor and ceiling do a shuffle's comparisons lie, on average?
  1. the move: a floor from the swaps

    the line:
    A≥n(n−1)4A \ge \frac{n(n - 1)}{4}

    why it is allowed: AA is the comparisons averaged over every shuffle. Every swap follows a comparison, so AA is at least the average swaps, line 12 of the ladder before.

  2. the move: a simpler floor

    the line:
    A≥n28 for n≥2A \ge \frac{n^2}{8} \text{ for } n \ge 2

    why it is allowed: The ladder before shows that n(n−1)4\frac{n(n - 1)}{4} is at least n28\frac{n^2}{8} from 2 numbers on, in its lines 12 to 19.

  3. the move: read it as a bound

    the line:
    A∈Ω(n2)A \in \Omega(n^2)

    why it is allowed: By line 2.

  4. the move: a ceiling from the dearest rows

    the line:
    A≤n(n−1)2A \le \frac{n(n - 1)}{2}
    numbersline 1the averageline 4
    31.5about 2.833
    55about 9.2610
    814about 2628
    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.

  5. the move: a simpler ceiling

    the line:
    A≤n22A \le \frac{n^2}{2}

    why it is allowed: The first ladder's line 14 writes line 4 as half of n2n^2 less half of nn, and its line 18 says that is at most half of n2n^2.

  6. the move: read it as a bound

    the line:
    A∈O(n2)A \in O(n^2)

    why it is allowed: By line 5.

  7. the move: a ceiling and a floor together

    the line:
    A∈Θ(n2)A \in \Theta(n^2)

    why it is allowed: Lines 3 and 6 bound AA by the same growth, n2n^2.

try it on small rows: over every order of 4 numbers, the average AA is about 5.58

Why does a row back to front take n(n−1)2\frac{n(n - 1)}{2} swaps, and why does no row take more?
  1. the move: every pair is wrong

    the line:
    on a row back to front,every pair is an inversion\begin{gathered} \text{on a row back to front,} \\ \text{every pair is an inversion} \end{gathered}

    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.

  2. the move: one swap for each

    the line:
    W=n(n−1)2W = \frac{n(n - 1)}{2}

    why it is allowed: WW 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.

  3. the move: no row takes more

    the line:
    no row takes more thann(n−1)2 swaps\begin{gathered} \text{no row takes more than} \\ \frac{n(n - 1)}{2} \text{ swaps} \end{gathered}

    why it is allowed: A row's swaps are its inversions, and it has no more inversions than pairs.

try it with a small nn: at n=4n = 4, line 2 gives W=6W = 6, which you can work out by hand

count it yourself

Count every step on four numbers back to front, then check the comparisons against n(n−1)2\frac{n(n - 1)}{2}. 4 times 3 over 2 is 6.

4, 3, 2, 1, every step written down
stepthe rowwhat happenscomparisonsswaps
14, 3, 2, 1There are 4 numbers in a row. Walk along it from the left, comparing each neighbouring pair.4, 3, 2, 100
24, 3, 2, 14 is bigger than 3, so they are the wrong way round.4, 3, 2, 110
33, 4, 2, 1Swap them: 3 moves left and 4 moves right.3, 4, 2, 111
43, 4, 2, 14 is bigger than 2, so they are the wrong way round.3, 4, 2, 121
53, 2, 4, 1Swap them: 2 moves left and 4 moves right.3, 2, 4, 122
63, 2, 4, 14 is bigger than 1, so they are the wrong way round.3, 2, 4, 132
73, 2, 1, 4Swap them: 1 moves left and 4 moves right.3, 2, 1, 433
83, 2, 1, 44 is now at the end of the unsorted part. Nothing bigger is left, so it stays there for good.3, 2, 1, 433
93, 2, 1, 43 is bigger than 2, so they are the wrong way round.3, 2, 1, 443
102, 3, 1, 4Swap them: 2 moves left and 3 moves right.2, 3, 1, 444
112, 3, 1, 43 is bigger than 1, so they are the wrong way round.2, 3, 1, 454
122, 1, 3, 4Swap them: 1 moves left and 3 moves right.2, 1, 3, 455
132, 1, 3, 43 is now at the end of the unsorted part. Nothing bigger is left, so it stays there for good.2, 1, 3, 455
142, 1, 3, 42 is bigger than 1, so they are the wrong way round.2, 1, 3, 465
151, 2, 3, 4Swap them: 1 moves left and 2 moves right.1, 2, 3, 466
161, 2, 3, 42 is now at the end of the unsorted part. Nothing bigger is left, so it stays there for good.1, 2, 3, 466
171, 2, 3, 4Only 1 is left, so it is in place too.1, 2, 3, 466
181, 2, 3, 4In order, after 6 comparisons and 6 swaps.1, 2, 3, 466

In all, 6 comparisons. The formula from section 4, n(n−1)2\frac{n(n - 1)}{2}, gives C=6C = 6 at n=4n = 4: 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 n−1n - 1 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.

comparisons on a shuffled row, on the log-log scales of section 2, one line for each way whose page is written
102104106108101010121014101102103104105106107cocktail shaker sortinsertion sortselection sortshell sortquick sortrandomised quick sortmerge sortheap sortbubble sort10110210310410510610710810910101011101210131014101102103104105106107cocktail shaker sortinsertion sortselection sortshell sortquick sortrandomised quick sortmerge sortheap sortbubble sort
  • bubble sort
  • cocktail shaker sort
  • insertion sort
  • selection sort
  • shell sort
  • quick sort
  • randomised quick sort
  • merge sort
  • heap sort
put a row in order: each way side by side
waybestaverageworstextra memorykeeps equal items in orderworks in placereach for it when
bubble sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)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 rowyesyesyou 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Θ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)a few spare places, the same however long the rowyesyesyou are learning how sorting works; for real work, insertion sort
insertion sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)room for a few numbers (the number being placed, where its slide has reached, which number is next), the same however long the rowyesyesthe row is short, a few dozen numbers, or nearly in order
selection sortΘ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)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 rownoyesmoving a number costs far more than comparing two, and the row is short
shell sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)not known; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)not worked out here; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)a few spare places (the gap, the number picked up, its place), the same however long the rownoyesyou 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Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2)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 rownonoyou 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 sortat most O(n log⁡2 n)O(n \,\log_2\, n), as every row of different numbers averages that over the picks; a row with equal numbers can cost a little lessΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2), a row of equal numbers, whatever the picks; no run costs more, since a pair meets at most oncea 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 rownonoyou want quick sort without a dear row in order, and equal items need not keep their order
merge sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)a second row as long as the rowyesnoyou need comparisons growing no faster than n log⁡2 nn \,\log_2\, n on every row, equal items kept in order, or a file too big for memory sorted
heap sortΘ(n)\Theta(n), every number the sameΘ(n log⁡2 n)\Theta(n \,\log_2\, n), shuffled; measured, no formula worked out hereΘ(n log⁡2 n)\Theta(n \,\log_2\, n), the dearest row; this page finds it only for short rows, by trying every ordera few places, however long the rownoyesyou need a sort with no slow row and no second row, and equal items need not keep their order
counting sortΘ(n)\Theta(n) steps, every row alikeΘ(n)\Theta(n) stepsΘ(n)\Theta(n) steps, every row alikea second row of n places and 10 talliesyesnothe numbers are small whole numbers, such as ratings from 0 to 9, and equal ones must keep their order
radix sortΘ(n)\Theta(n) placings, every number below 10Θ(n)\Theta(n) placings, between the best and the worst, as every order costs the sameΘ(n)\Theta(n) placings, three passes for numbers up to 999a second row of n places and 10 talliesyesnomany 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.

race them on one row of your own