Pattern visualizer
Bubble Sort
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. Animated on: Sort an array into ascending order by repeatedly swapping adjacent pairs that are out of order..
Watch the largest value bubble to the end, one pass at a time.
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