Pick · Compare · Shift · Insert · O(n) best case
| BUBBLE SORT | INSERTION SORT | |
|---|---|---|
| Method | Swap adjacent pairs | Shift and insert |
| Uses TEMP? | Yes (3-line swap) | No — just shift |
| Inner loop | FOR going right | WHILE going left |
| Best case | O(n)* | O(n) |
| Worst case | O(n²) | O(n²) |
key = data[i] — save the current element before any shifting happens. Shifting will overwrite data[i], so we must save the value first.j = i − 1 — j starts at the last element of the sorted portion and moves left.j ≥ 0 AND data[j] > key. Both conditions must be true. The first stops us going past the start. The second stops when we've found where key belongs.data[j+1] = data[j] — shift the element one place right. Then j = j − 1 — move left.data[j+1] = key — place the saved key into the gap. No TEMP variable. No swap.data[j+1] = data[j] — one line, moves element right. Then after loop: data[j+1] = key — inserts. No TEMP, no three-line swap.| PASS | KEY | SHIFTS | ARRAY AFTER |
|---|---|---|---|
| 1 | 3 | 1 | [3, 5, 8, 1, 4] |
| 2 | 8 | 0 | [3, 5, 8, 1, 4] |
| 3 | 1 | 3 | [1, 3, 5, 8, 4] |
| 4 | 4 | 2 | [1, 3, 4, 5, 8] |
| PASS | i | KEY | j COMPARISONS | SHIFTS | ARRAY AFTER |
|---|---|---|---|---|---|
| 1 | 1 | 4 | j=0: 6>4 ✓ | 1 | [4, 6, 3, 5] |
| 2 | 2 | 3 | j=1: 6>3 ✓ j=0: 4>3 ✓ | 2 | [3, 4, 6, 5] |
| 3 | 3 | 5 | j=2: 6>5 ✓ j=1: 4>5 ✗ | 1 | [3, 4, 5, 6] ✓ |
| BUBBLE | INSERTION | MERGE | |
|---|---|---|---|
| Best | O(n)* | O(n) | O(n log n) |
| Average | O(n²) | O(n²) | O(n log n) |
| Worst | O(n²) | O(n²) | O(n log n) |
| Memory | In-place | In-place | Extra needed |
| Nearly sorted | Good* | Excellent | O(n log n) |
arr[back+1] = arr[back] (shift, inside loop) then arr[back+1] = current (insert, after loop). No TEMP.val = list[n] extracts the key before the inner loop / inner WHILE loop moves leftward (p = p−1) checking list[p] > val / shift without TEMP: list[p+1] = list[p], then insert: list[p+1] = val (1 mark each, max 2)Next up: 2.2.1a — Variables, Constants & Data Types