Compare · Swap · Repeat · Optimise
data[j] > data[j+1], and three-line swap using a TEMP variabledata[j] = data[j+1] first, you'd overwrite data[j] and lose it forever. The TEMP variable preserves the original value:data[j] > data[j+1], and the three-line TEMP swap. All three together = bubble sort.FOR i = 0 TO LEN-2 — outer loop. Runs n−1 times; each pass guarantees one more element is in place.FOR j = 0 TO LEN-2-i — inner loop. The -i means each pass does one fewer comparison (last i elements already sorted).data[j] > data[j+1] — adjacent comparison. j+1 is the key — it's always the next element, not some fixed index.temp / data[j] / data[j+1] — three-line swap. The order matters: save → overwrite → restore from TEMP.data[j] > data[j+1] to data[j] < data[j+1]. Everything else stays the same. The comparison direction is the only change.LEN-2-i as its upper bound.swapped=FALSE → stops immediately.| Pass (i) | Array after pass | Swaps | Element placed |
|---|---|---|---|
| — | [4, 2, 7, 1, 5] | — | Initial state |
| 0 | [2, 4, 1, 5, 7] | 3 | 7 → index 4 |
| 1 | [2, 1, 4, 5, 7] | 1 | 5 → index 3 |
| 2 | [1, 2, 4, 5, 7] | 1 | 4 → index 2 |
| 3 | [1, 2, 4, 5, 7] | 0 | SORTED ✓ |
swapped=FALSE triggers the early exit. Without optimisation, this pass still runs.swapped = TRUE at the start — ensures the WHILE loop runs at least once.swapped = FALSE at the start of each pass — assume this pass will make no swaps.swapped = TRUE inside the IF — if ANY swap happens, set the flag back to TRUE.swapped is still FALSE, no swap occurred → list is sorted → WHILE exits.| LINEAR SEARCH | BINARY SEARCH | BUBBLE SORT | |
|---|---|---|---|
| Type | Search | Search | Sort |
| Needs sorted? | No | Yes | No |
| Best case | O(1) | O(1) | O(n)* |
| Worst case | O(n) | O(log n) | O(n²) |
| Large data | Slow | Fast | Very slow |
data[j] and data[j+1] — j+1 is always j's neighbour. (3) Three-line TEMP swap. All three together = bubble sort, regardless of variable names.data[j] = data[j+1] first overwrites and loses data[j].data[j] > data[j+1]. (3) Three-line TEMP swap. All three = bubble sort.Next up: 2.1.3d — Merge Sort