Bubble Sort
Watch the largest value bubble to the end, one pass at a time.
Swapping two adjacent out-of-order values fixes one local disorder and can never undo an earlier fix, so repeating it across the array only ever moves things closer to sorted. Walking left to right, whichever value is currently the largest keeps winning every comparison it's part of, so it gets carried step by step all the way to the end of the pass — that's why a single full sweep is guaranteed to plant the maximum in its correct slot even though nothing else is settled yet. Bubble sort repeats this sweep, and the sorted region grows from the right until a whole pass makes no swaps.
Details
Animated on: Sort an array into ascending order by repeatedly swapping adjacent pairs that are out of order.
Problem:Bubble SortEasy
Watch the largest value bubble to the end, one pass at a time.
step 1 / 15
Start with an unsorted array. Bubble sort will float the largest remaining value to the right end on every pass.
1FOR i from 0 to n-1:2 FOR j from 0 to n-2-i:3 IF arr[j] > arr[j+1]:4 swap arr[j] and arr[j+1]
← / → step · space play · Home restart
Every step in words
Show all 15 steps
- Start with an unsorted array. Bubble sort will float the largest remaining value to the right end on every pass.
- Compare the pair 5 and 2. Since 5 > 2 they are out of order, so swap — the larger value edges one step toward the tail.
- 5 is now at index 1. Compare 5 and 4: 5 > 4, swap. The largest value keeps bubbling rightward.
- Compare 5 and 1: 5 > 1, swap. Each comparison carries the biggest value one cell further right.
- Compare 5 and 3: 5 > 3, swap. 5 reaches the last slot of the array.
- Pass 1 complete. 5 is the maximum and is now locked in its correct place — the sorted region (green) starts growing from the right.
- Pass 2 begins and ignores the settled 5. Compare 2 and 4: 2 < 4, already in order, so no swap.
- Compare 4 and 1: 4 > 1, swap. 4 is the biggest un-settled value and now starts bubbling right.
- Compare 4 and 3: 4 > 3, swap. 4 comes to rest just left of 5.
- Pass 2 complete. 4 is locked in beside 5 — the sorted tail is now two cells wide.
- Pass 3 begins. Compare 2 and 1: 2 > 1, swap so the smaller value moves left.
- Compare 2 and 3: 2 < 3, already in order — no swap needed.
- Pass 3 complete. 3 settles into place; only the first two cells remain unsorted.
- Pass 4: compare 1 and 2: 1 < 2, already in order — no swap.
- No swap was needed this pass, and every neighbour is in order — the array is fully sorted.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.