The interactive player is loading. If it does not appear, you can still read the explanation below.
How it works
Bubble sort compares neighboring values from left to right and swaps them when the left value is greater. After each pass, the largest remaining value is in its final position. The next pass checks a shorter range.
This version stops early when a pass makes no swaps. An already sorted array needs n − 1 comparisons for n ≥ 1: O(n) best-case time. Reversed distinct values need n(n − 1) / 2 comparisons and swaps: O(n²) worst-case time. For uniformly random permutations of distinct values, average time is O(n²).
Equal values never swap with each other, so their original order is preserved: the sort is stable. Empty arrays and single values are already sorted. The algorithm uses O(1) extra space; storing snapshots for the animation requires additional memory.