Sorting algorithms
Bubble, selection and insertion sort with dry runs and analysis.
The essentials
Sorting arranges elements in a particular order, such as ascending. Sorted data is easier to search (binary search needs it) and to read. Three simple methods are studied: bubble sort, selection sort and insertion sort. For a list of n elements, each makes up to n − 1 passes.
Key points
- Bubble sort: compare adjacent pairs and swap them if they are in the wrong order. After each pass, the largest remaining element "bubbles up" to its final position at the end. Example pass 1 on [5, 1, 4, 2, 8] gives [1, 4, 2, 5, 8]. Without early stopping, it makes n(n − 1)/2 comparisons. An optimised version stops if a pass makes no swaps, so a sorted list needs only one pass.
- Selection sort: in each pass, find the smallest element in the unsorted part and swap it with the first element of that part. Pass 1 on [29, 10, 14, 37, 13] gives [10, 29, 14, 37, 13]; pass 2 gives [10, 13, 14, 37, 29]. It makes n(n − 1)/2 comparisons in every case but at most one swap per pass.
- Insertion sort: take elements one at a time from the unsorted part and insert each into its correct place in the sorted part on the left, shifting larger elements right. After two passes on [8, 4, 6, 2, 9], the list is [4, 6, 8, 2, 9].
- Insertion sort cases: best case (already sorted) needs only n − 1 comparisons; worst case (reverse sorted) needs n(n − 1)/2.
- All three are said to take time proportional to n² in the worst case, written O(n²).
Exam tips
- Know what is guaranteed after pass k: bubble sort fixes the k largest at the end; selection sort fixes the k smallest at the start.
- In insertion sort the left part is sorted, but its elements may not yet be in their final positions.
Common mistakes
- Selecting the largest element in selection sort when the question asks for ascending order with smallest-first.
- Counting the comparisons of one pass instead of the whole sort.
Practice questions
Log in to answer these questions and see the explanations.Create free accountLog in