Bubble Sort

Bubble sort puts a list in order by repeatedly comparing neighbouring elements and swapping any pair that is out of order. It is rarely the fastest choice. It is, however, the sorting algorithm you are most likely to trace by hand on a test, and a clean setting for learning to count the work an algorithm does. Throughout this lesson the goal is ascending order, and each pass scans from left to right.



How one pass works

A pass is one sweep through the unsorted part of the list. You compare positions 1 and 2, then 2 and 3, and so on, swapping whenever the left value is larger than the right. When the sweep meets the largest value of the unsorted part, that value wins every later comparison and is carried all the way to the end, the way a bubble rises to the surface. That gives the key invariant: after pass kk, the kk largest values sit in their final positions, so each new pass can stop one position earlier.


Example: Start with [6, 2, 9, 4, 3]. The pair 6, 2 is swapped, 6 and 9 stay where they are, then 9 is swapped past 4 and past 3. After four comparisons and three swaps the list is [2, 6, 4, 3, 9], and 9 never moves again.


Five rows of five boxes trace the comparisons in the first pass of bubble sort, with the compared pair shaded blue and the final value 9 shaded green.


If a whole pass makes no swaps, every adjacent pair is already in order, so the entire list is sorted. The early-exit version records this with a flag and stops:


Python
def bubble_sort(a):
    n = len(a)
    for end in range(n - 1, 0, -1):
        swapped = False
        for i in range(end):
            if a[i] > a[i + 1]:
                a[i], a[i + 1] = a[i + 1], a[i]
                swapped = True
        if not swapped:
            break
    return a



Counting comparisons and swaps

For a list of nn elements, pass 1 makes n−1n-1 comparisons, pass 2 makes n−2n-2, and so on down to 1. When every pass is needed, the total is


C=(n−1)+(n−2)+⋯+2+1=n(n−1)2C = (n-1) + (n-2) + \cdots + 2 + 1 = \frac{n(n-1)}{2}


Swaps follow a different rule. An inversion is a pair of values that appear in the wrong order relative to each other, whether or not they are next to each other. Swapping an adjacent out-of-order pair removes exactly one inversion and creates none, so the total number of swaps equals the number of inversions in the starting list. The list [3, 1, 2] contains two inversions, (3, 1) and (3, 2), so bubble sort sorts it with exactly two swaps.


The growth column below uses Big-O notation.


Input order

Comparisons (early exit)

Swaps

Growth

Already sorted (best)

n−1n-1

00

O(n)O(n)

Random order of distinct values (average)

close to n(n−1)/2n(n-1)/2 for large nn

n(n−1)/4n(n-1)/4 on average

O(n2)O(n^2)

Reverse sorted (worst)

n(n−1)/2n(n-1)/2

n(n−1)/2n(n-1)/2

O(n2)O(n^2)



Strengths and limits

Bubble sort is in place and stable, and with the early exit it finishes in a single pass on a list that is already sorted. Its weakness is the quadratic worst case: a reversed list of 10,000 elements needs 49,995,000 comparisons. Small values near the end are also slow to move, because a value travels left by at most one position per pass. The list [2, 3, 4, 5, 1] needs four passes even though moving a single value would fix it.

What to remember

  • Each pass compares adjacent pairs and carries the largest unsorted value to the end.
  • Pass kk makes n−kn-k comparisons; all passes together make n(n−1)/2n(n-1)/2.
  • The total number of swaps equals the number of inversions in the starting list.
  • A pass with no swaps means the list is sorted, so the early-exit version stops.
  • Best case O(n)O(n) with early exit; average and worst case O(n2)O(n^2).

Example: Tracing an early-exit bubble sort

A program sorts the list 4, 2, 1, 5, 3, 6 into ascending order with an early-exit bubble sort. Each pass compares adjacent pairs from left to right across the unsorted part and swaps a pair when the left value is larger. The unsorted part shrinks by one position after every pass, and the program stops after the first pass that makes no swaps.


a) Trace pass 1. Give the list after the pass and the number of swaps it makes.


Nothing is known to be in place yet, so pass 1 compares all five adjacent pairs.

  • 4>24 > 2, swap. The list becomes ________.
  • 4>14 > 1, swap. The list becomes ________.
  • 4<54 < 5, no swap.
  • 5>35 > 3, swap. The list becomes 2, 1, 4, 3, 5, 6.
  • 5<65 < 6, no swap.

After pass 1 the list is 2, 1, 4, 3, 5, 6, and the pass made 3 swaps. The largest value, 6, holds the last position and is now treated as sorted.


b) Trace passes 2 and 3, and explain why the program stops after pass 3.


Pass 2 works on the first five positions, 2, 1, 4, 3, 5, so it makes ________ comparisons.

  • 2>12 > 1, swap. The list becomes ________.
  • 2<42 < 4, no swap.
  • 4>34 > 3, swap. The list becomes 1, 2, 3, 4, 5, 6.
  • 4<54 < 5, no swap.

Pass 2 made ________ swaps. The list happens to be sorted now, but the program cannot know that yet: a pass that made swaps may have left other pairs out of order.


Pass 3 works on the first four positions, making ________ comparisons: 1 and 2, 2 and 3, 3 and 4. Every pair is already in order, so the swapped flag stays false. A pass with no swaps proves that every adjacent pair is in order, so the program stops after pass 3 with the list 1, 2, 3, 4, 5, 6.


c) Find the total number of comparisons and swaps. How many comparisons does the early exit save compared with a version that always runs every pass?


Add the work pass by pass:


comparisons=5+4+3=12,swaps=3+2+0=5\text{comparisons} = 5 + 4 + 3 = 12, \qquad \text{swaps} = 3 + 2 + 0 = 5


Check the swaps by counting inversions in the starting list 4, 2, 1, 5, 3, 6. The out-of-order pairs are (4, 2), (4, 1), (4, 3), (2, 1) and (5, 3), so there are ________ inversions, matching the five swaps.


A version without the early exit runs all five passes, so it makes ________ comparisons:


5+4+3+2+1=6×52=155 + 4 + 3 + 2 + 1 = \frac{6 \times 5}{2} = 15


The early exit saves 15−12=315 - 12 = 3 comparisons. The swap count is 5 either way, because passes 4 and 5 would find no out-of-order pairs.

Bubble sort is sorting a list of 10 distinct integers into ascending order, comparing adjacent pairs from left to right and swapping whenever the left value is larger. After the third pass is complete, which statement is guaranteed to be true?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Match each bubble sort term with the description that fits it. Each description is used exactly once, and every description refers to sorting a list of values into ascending order.

Match each term
A.

A Boolean reset before each sweep and set when an exchange happens; if it stays false, the algorithm stops early

B.

The positions at the end of the list that already hold their final values after k sweeps

C.

Input in strictly decreasing order, which needs n(n − 1)/2 exchanges

D.

One sweep through the unsorted part of the list, comparing each neighbouring pair in turn

E.

Needs only a constant amount of extra memory beyond the list itself

F.

A pair of positions i < j where the earlier value is larger than the later value

Swap flag

Worst case

Pass

In-place

Sorted tail

Inversion

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Arrange the steps of one pass of an early-exit bubble sort that sorts a list into ascending order, from the first step of the pass to the decision made at its end.

Loading ordering steps…

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice