CAP7004 · Unit 3: Searching and sorting
Bubble, selection and insertion sort
8 practice questions
Key points
- All three are O(n^2) in the worst case
- Bubble and insertion are stable and O(n) when already sorted
- Selection always does n(n-1)/2 comparisons
- Insertion sort is good for nearly sorted data
Three simple O(n^2) comparison sorts.
| Sort | Idea | Best | Average / Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Bubble | Swap adjacent out-of-order pairs; largest moves to the end each pass | O(n) with early exit | O(n^2) | O(1) | Yes |
| Selection | Pick the minimum of the unsorted part, swap it to the front | O(n^2) | O(n^2) | O(1) | No |
| Insertion | Insert each item into the sorted prefix by shifting larger items right | O(n) | O(n^2) | O(1) | Yes |
Worked traces:
- Bubble sort on
[5, 1, 4, 2, 8]: after one pass[1, 4, 2, 5, 8]; it finishes after 3 passes with 4 swaps in total (the third pass makes no swaps, so the early exit stops). - Selection sort on
[64, 25, 12, 22, 11]: after one pass[11, 25, 12, 22, 64]; always 10 comparisons for n = 5. - Insertion sort on
[5, 2, 4, 6, 1, 3]makes 9 shifts. On a reversed list of n items it makes n(n-1)/2 shifts, on a sorted list 0.
Stable means equal keys keep their original order. Insertion sort is excellent for small or nearly sorted input.
Exam pitfall: selection sort does the same number of comparisons even for sorted input; its swaps are at most n - 1.
Try two questions
Selection sort repeatedly:
- Splits the list in halves and merges them
- Swaps adjacent items that are out of order
- Builds a heap and extracts the maximum
- Selects the minimum of the unsorted part and swaps it into place
Show the answer
D. After each pass the next smallest value is fixed in position.
Bubble sort on [5, 1, 4, 2, 8]: the list after the first pass is:
- [5, 1, 4, 2, 8]
- [1, 5, 4, 2, 8]
- [1, 2, 4, 5, 8]
- [1, 4, 2, 5, 8]
Show the answer
D. The largest value among the first four moves right by adjacent swaps only: [1, 4, 2, 5, 8].