Bubble Sort visualization

Repeatedly swap adjacent out-of-order pairs; the largest value bubbles to the end each pass.

Each pass walks the array comparing neighbours. Whenever the left one is larger, they swap — so the biggest unsorted value is carried to the end like a bubble rising.

After pass k the last k positions are final. If a pass makes no swaps, the array is already sorted and we stop early, which is why the best case is O(n).

Complexity

Time: best O(n), average O(n²), worst O(n²). Space: O(1). Difficulty: Beginner.

Pseudocode

procedure bubbleSort(A):
  for i ← 0 to n−2:
    swapped ← false
    for j ← 0 to n−i−2:
      if A[j] > A[j+1]:
        swap(A[j], A[j+1]); swapped ← true
    if not swapped: break
  return A

More sorting algorithms