Data Structures · Sorting

Bubble Sort

🔢 The array a[]

not sorted yet comparing a[j] with a[j+1] just swapped (out of order → exchanged) settled (each pass pins one maximum)
pass i = 0 comparisons 0 swaps 0 settled 0 / 6
result(not finished yet)

🧾 Pass-by-pass record

PassComparisonsSwapsArray after the passNote

💬 Current step

💻 The algorithm (courseware-style C++)

Yellow = the line being executed. Bubble sort compares neighbours and swaps them when they are out of order — after every pass the largest value has bubbled to the end, so the next pass ignores it.

📄 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.
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result