How bubble sort works
Each pass compares every adjacent pair, arr[j] and arr[j + 1], and swaps them when the left one is larger. The largest value not yet in place is carried all the way to the end, like a bubble rising — so after pass i the last i elements are final, and the inner loop can stop i positions earlier.
The Python example sorts [5, 2, 9, 1, 7]. The outer loop counts passes; the inner loop’s range, n − i − 1, shrinks by one each time, which is the only optimisation this version makes.
What to watch for when it runs
- The two cells being compared light up on every step, and a swap animates them trading places.
- The sorted tail grows from the right by one cell per pass.
- The execution count on the comparison line climbs to n(n − 1) / 2 — that number is the O(n²).
Time and space complexity
- Time
- O(n²)
- Space
- O(1)
This version always makes n(n − 1) / 2 comparisons. Stopping early when a pass makes no swaps brings an already-sorted array down to O(n).