📄 Key points
1Compare neighbours — look only at the pair a[j] and a[j+1]
2Swap when out of order — a[j] > a[j+1] means they are the wrong way round
3One value per pass — after pass i the largest value sits at a[n−1−i]
40 swaps → stop early — a pass with no swap means it is already sorted, break
Why “bubble”? During a pass the larger element keeps swapping with its right-hand neighbour, floating like a bubble to the end of the unsorted part (sorting ascending, the maximum travels right).
Complexity: comparisons = (n−1) + (n−2) + … + 1 = n(n−1)/2 → time O(n²); with the swapped flag an already sorted array costs one pass of n−1 comparisons and 0 swaps → O(n); extra space O(1).
Properties: it swaps only neighbours and never swaps equal values, so bubble sort is stable (equal values keep their relative order); it does many swaps, though, so it is rarely used on large arrays.
In this demo: six reversed numbers need 5 passes / 15 comparisons / 15 swaps — the worst case.