Bubble sort walks through the array comparing neighbors and swapping any pair that is out of order. Each pass carries the largest remaining value to the end, like a bubble rising to the top. It is the simplest sort to describe, and a good way to see why some sorts are faster than others.
One pass walks from the left end of the array to the right, looking at each pair of neighbors arr[j] and arr[j + 1]:
arr[j] > arr[j + 1], the pair is in the wrong order, so swap them.The largest value is swapped along every step of the way, so at the end of the pass it sits in the last position, its final place. The array now has two parts:
Stopping early. If a whole pass makes no swaps, every pair of neighbors is in order, so the whole array is sorted and the algorithm can stop. The code keeps a swapped flag to notice this.
Sorting {5, 1, 4, 2, 8}. Each row shows the array after a pass. Blue cells are in their final place.
The array in main() changes to match what you sort.
Worst case. On reversed input every pass runs to the end of the unsorted part and swaps every pair. Pass 1 compares n − 1 pairs, pass 2 compares n − 2, and so on, for
(n − 1) + (n − 2) + … + 1 = n(n − 1) / 2
comparisons and as many swaps: O(n²). Random input is also O(n²) on average.
Best case. On input that is already sorted, the first pass makes n − 1 comparisons and no swaps, so the swapped flag stops the sort right there: O(n). Bubble sort is adaptive: the closer the data is to sorted, the less work it does.
Swaps. Each swap fixes exactly one pair of values that are out of order (an inversion), so the number of swaps equals the number of inversions in the input. That can be up to n(n − 1)/2, far more than the n − 1 swaps selection sort needs.
Memory. It sorts in place: O(1) extra space.
swapped flag, O(n) on data that is already sorted, and fast on data that is nearly sorted.The largest value. Whenever the pass reaches it, it is bigger than its right neighbor, so it gets swapped right at every step until it reaches the end.
After i passes, the last i positions already hold the i largest values in order. There is no need to compare them again, and the − 1 keeps arr[j + 1] inside the array.
On the sorted array, 5: one pass with no swaps, then it stops. On the reversed array, 5 + 4 + 3 + 2 + 1 = 15 comparisons and 15 swaps.
Equal neighbors would be swapped too, so bubble sort would no longer be stable, and it would make extra, useless swaps. With >=, any array with two equal neighbors would always record a swap, so the early stop could never happen.