Bubble, selection and insertion sort as the textbook codes them, pass by pass, with their swaps, shifts and comparisons, and their time complexity.
| Bubble, pass 1 | 5, 1, 4, 2, 8 → 1, 4, 2, 5, 8 (3 swaps) |
| Selection, pass 1 | 5, 1, 4, 2, 8 → 1, 5, 4, 2, 8 (1 and 5 swap places) |
| Insertion, passes 1 and 2 | 5, 1, 4, 2, 8 → 1, 5, 4, 2, 8 → 1, 4, 5, 2, 8 |
| Bubble comparisons, n items | n(n − 1)/2: 6 items → 15 |
| Total swaps or shifts | the number of pairs out of order: in 5, 1, 4, 2 the pairs 5 1, 5 4, 5 2, 4 2 give 4 |
| Decreasing order | bubble sort swaps when the left item is the smaller |
Sort 29, 12, 28, 54, 47, 31 into increasing order (a) by selection sort and (b) by insertion sort, writing the list after every pass.
Working: selection: swap the smallest of the rest to the front; insertion: insert the next item into the sorted left part
Answer: (a) 12, 29, 28, 54, 47, 31 → 12, 28, 29, 54, 47, 31 → 12, 28, 29, 54, 47, 31 → 12, 28, 29, 31, 47, 54 → 12, 28, 29, 31, 47, 54; (b) 12, 29, 28, 54, 47, 31 → 12, 28, 29, 54, 47, 31 → 12, 28, 29, 54, 47, 31 → 12, 28, 29, 47, 54, 31 → 12, 28, 29, 31, 47, 54