Bubble Sort
O(n²)

History

Bubble Sort is perhaps the most well-known sorting algorithm, often taught as an introduction to sorting concepts. The name comes from the way smaller elements 'bubble' to the top of the list. It was analyzed as early as 1956 by mathematician Edward Friend. Despite being inefficient for most real-world applications, it's valuable for educational purposes and can be optimized with an early termination flag.

How it works

  1. Compare adjacent elements from the beginning
  2. Swap them if they are in the wrong order
  3. Continue to the end of the array
  4. Repeat passes until no swaps are needed

When to use

  • Educational purposes: Easy to understand and implement
  • Detecting sorted arrays: With early termination optimization
  • Very small datasets: Where simplicity matters more than speed

Implementation

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        swapped = False
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break
    return arr
function bubbleSort(arr) {
    const n = arr.length;
    for (let i = 0; i < n; i++) {
        let swapped = false;
        for (let j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
                swapped = true;
            }
        }
        if (!swapped) break;
    }
    return arr;
}
func bubbleSort(arr []int) []int {
    n := len(arr)
    for i := 0; i < n; i++ {
        swapped := false
        for j := 0; j < n-i-1; j++ {
            if arr[j] > arr[j+1] {
                arr[j], arr[j+1] = arr[j+1], arr[j]
                swapped = true
            }
        }
        if !swapped {
            break
        }
    }
    return arr
}
fn bubble_sort<T: Ord>(arr: &mut [T]) {
    let n = arr.len();
    for i in 0..n {
        let mut swapped = false;
        for j in 0..n - i - 1 {
            if arr[j] > arr[j + 1] {
                arr.swap(j, j + 1);
                swapped = true;
            }
        }
        if !swapped { break; }
    }
}

Complexity

Best Case O(n)
Average Case O(n²)
Worst Case O(n²)
Space O(1)
Stable Yes

Try it yourself

See this algorithm in action with the visualizer.

Run