← Back to DSA
🫧

Sorting

Bubble Sort

Repeatedly swaps adjacent elements that are out of order, "bubbling" the largest unsorted element to its correct position each pass.

Complexity

Time (Best)

O(n)

Time (Avg)

O(n²)

Time (Worst)

O(n²)

Space

O(1)

Key Points

  • ›Simple to implement but inefficient for large datasets
  • ›Each full pass places one more element in its final sorted position
  • ›Optimizable: if no swaps occur in a pass, the array is already sorted — exit early
  • ›Stable sort: preserves relative order of equal elements
  • ›In-place: requires only O(1) extra space

Interactive Visualizer

Step 0 / 0✓ Sorted!
SlowFast
DefaultComparingSwappingSorted

Code Examples

Swift
func bubbleSort(_ arr: inout [Int]) {
    let n = arr.count
    for i in 0..<n - 1 {
        var swapped = false
        for j in 0..<n - i - 1 {
            if arr[j] > arr[j + 1] {
                arr.swapAt(j, j + 1)
                swapped = true
            }
        }
        if !swapped { break }  // early exit optimisation
    }
}

var nums = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(&nums)
print(nums)  // [11, 12, 22, 25, 34, 64, 90]

Practice Problems

Sort Colors
Sort an Array