beginnersorting

Bubble Sort

Bubble Sort

Bubble sort is the simplest sorting algorithm to understand. It repeatedly steps through the array, compares adjacent elements, and swaps them if they're in the wrong order. Each pass "bubbles" the largest unsorted element to its correct position at the end.

How It Works

  1. Compare each pair of adjacent elements
  2. If the left element is larger, swap them
  3. After one pass, the largest element is at the end
  4. Repeat for the remaining unsorted portion
  5. Stop early if a pass makes no swaps (array is sorted)

Code Snippet

def bubble_sort(numbers: list[int]) -> list[int]:
    """Sort by repeatedly swapping adjacent out-of-order pairs."""
    array_length = len(numbers)

    for pass_number in range(array_length - 1):
        swapped_this_pass = False

        for current_position in range(array_length - 1 - pass_number):
            current_value = numbers[current_position]
            next_value = numbers[current_position + 1]

            if current_value > next_value:
                numbers[current_position] = next_value
                numbers[current_position + 1] = current_value
                swapped_this_pass = True

        # Early exit: if no swaps occurred, array is already sorted
        if not swapped_this_pass:
            break

    return numbers

Why O(n^2)

  • The outer loop runs up to n-1 times (one pass per element)
  • The inner loop runs up to n-1-pass comparisons per pass
  • Total comparisons: approximately n^2 / 2

Even with the early-exit optimization, the worst case (reverse-sorted input) still requires all n^2/2 comparisons.

When Bubble Sort is Acceptable

  • Teaching: It's the easiest sorting algorithm to understand and visualize
  • Nearly sorted data: With early exit, it's O(n) on already-sorted arrays
  • Tiny arrays: For n < 10, the simplicity outweighs the performance cost

When to Avoid It

For any practical sorting task with more than ~20 elements, use quicksort, merge sort, or your language's built-in sort. Bubble sort's O(n^2) makes it 10,000x slower than O(n log n) algorithms at n = 10,000.