Bubble Sort

Watch adjacent elements compared and swapped — the largest values "bubble" to the end

Speed: 400ms
Pass: 0 Comparisons: 0 Swaps: 0
Unsorted
Comparing
Swapping
Sorted
Press Step or Play to begin Bubble Sort

How Bubble Sort Works

Bubble Sort repeatedly walks through the list, compares adjacent elements, and swaps them if they are in the wrong order. After each pass, the largest unsorted element "bubbles up" to its correct position at the end.

for i = 0 to n-1:
  swapped = false
  for j = 0 to n-i-2:
    if arr[j] > arr[j+1]:
      swap(arr[j], arr[j+1])
      swapped = true
  if not swapped: break // early termination

Time complexity: Best case O(n) when the array is already sorted (one pass, no swaps → early termination). Average and worst case O(n²).

Space complexity: O(1) — sorts in place, only needs a temporary variable for swapping.

Key insight: After pass 1, the largest element is guaranteed to be at the end. After pass 2, the two largest are in place. The sorted region grows from right to left with each pass.