Given an array of integers nums, sort the array in ascending order using the Bubble Sort algorithm — repeatedly step through the array, compare each pair of adjacent elements, and swap them if they're in the wrong order. Each full pass "bubbles" the largest remaining element to its correct position at the end.
nums = [5,2,9,1,5,6][1,2,5,5,6,9]Invariant: after pass i completes, the last i elements are the i largest values, in sorted position. Each inner pass "bubbles" the current largest unsorted element rightward one swap at a time until it reaches its resting place. The early-exit swapped flag turns best-case (already sorted) input into O(n).
Bubble sort is the simplest sort to understand. It is too slow for big inputs, but it teaches how swaps move elements.
Walk from left to right, comparing each pair of neighbours. If the left one is bigger, swap them. After one pass, the largest value has bubbled to the end, where it stays. Repeat on the shorter unsorted part. If a pass makes no swap at all, the array is already sorted, so stop early.
Each pass bubbles the largest remaining value to the end. The swapped flag makes the best case linear.
Run the animation above on your own input, or watch the 1:42 video explanation of Bubble Sort with a dry run and Java code.