3 / 7 · Basic
Sorting 1: bubble, selection and insertion sort
Selection sort makes exactly 45 comparisons on any list of 10 values, whether the list starts shuffled or already in order.
Jump to the 11 practice questionsYou will learn
- Follow bubble, selection and insertion sort step by step
- Predict swaps from inversions
Before this: Searching: linear and binary search
1Explain
Putting things in order
This unit covers three simple methods. All three work by comparing two values at a time and moving values around inside the same list. They are short to write and easy to follow, and all three slow down sharply on long lists. Watching why they slow down is the best preparation for the faster methods in the next unit. Throughout, we count two things: comparisons (asking "is this value bigger than that one?") and swaps (exchanging two values).
2Explore
Bubble sort
Bubble sort walks along the list comparing each pair of neighbours. When the left one is bigger, it swaps them. After one full pass, the largest value has been carried step by step to the far right, like a bubble rising, and it never needs to move again. The next pass can stop one place earlier. A common improvement is to watch for a pass with no swaps at all: that means everything is already in order, so the sort can stop early.
Yellow bars are being compared; orange bars have just swapped; green bars are in their final place.
3Problem
Comparisons in bubble sort
How many comparisons does bubble sort (with the early stop) make on [5, 1, 4, 2, 8]?
Hint
Passes of 4, 3 and 2 comparisons; the third pass swaps nothing.
Solution
Answer: 9
Each pass compares the neighbouring pairs that are still unsorted: 4, 3 and 2 comparisons. The third pass makes no swap, so it stops.
4Problem
After the first pass
After the first pass of bubble sort, which value is certainly in its final place?
Hint
Follow the biggest value through the first pass.
Solution
Answer: The largest, at the end
The largest value wins every comparison it is in, so it is carried all the way to the end.
5Explore
Selection sort
Selection sort works the way many people sort a hand of cards. Scan the whole list for the smallest value and swap it into the first position. Then scan the rest for the smallest remaining value and swap it into the second position, and so on. On [5, 1, 4, 2, 8] the first scan finds 1 and swaps it with 5. The second finds 2 and swaps it with 5.
Blue marks the smallest value found so far in this scan. One swap at the end of the scan, if needed.
6Problem
Selection sort on 10 values
How many comparisons does selection sort make on any list of 10 values?
Hint
9 + 8 + … + 1.
Solution
Answer: 45
Selection sort scans all the values still unsorted, so it compares 9, then 8, down to 1, whatever the starting order: 9 + 8 + … + 1 = 10 × 9 / 2 = 45.
7Problem
Fewest swaps
Which method does the fewest swaps on [5, 1, 4, 2, 8]?
Hint
Count the swaps on the three counters you have seen.
Solution
Answer: Selection sort
Selection sort makes at most one swap per pass, so it makes 2 swaps here; bubble and insertion sort swap neighbours one at a time and make 4 each.
8Explore
Insertion sort
Insertion sort keeps the left part of the list sorted and grows it one value at a time. It takes the next value and moves it left, swapping with its neighbour, until the neighbour is not bigger. Then that value is in place among the sorted ones. On a list that is already nearly in order, each new value moves only a step or two, so insertion sort is very quick there.
The blue bar is the value being inserted. It moves left, one swap at a time, until its left neighbour is not bigger.
9Problem
Insertion sort on [3, 1, 2]
Put the list [3, 1, 2] in the order it passes through during insertion sort.
- [3, 1, 2]
- [1, 2, 3]
- [1, 3, 2]
Hint
First 1 slides past 3, then 2 slides past 3.
Solution
Answer:
- [3, 1, 2]
- [1, 3, 2]
- [1, 2, 3]
1 slides left past 3, then 2 slides left past 3 and stops after 1.
10Explain
Counting the swaps: inversions
There is a neat way to predict how many swaps bubble sort and insertion sort need. Count the inversions: pairs of values that are in the wrong order relative to each other. In [5, 1, 4, 2, 8] the inversions are (5, 1), (5, 4), (5, 2) and (4, 2), four in all. Each swap of two neighbours that are out of order fixes exactly one inversion and creates none, so both methods make exactly 4 swaps.
| Method | Example | Sorted (5 values) | Reversed (4 values) |
|---|---|---|---|
| Bubble sort | 9 / 4 | 4 / 0 | 6 / 6 |
| Selection sort | 10 / 2 | 10 / 0 | 6 / 2 |
| Insertion sort | 7 / 4 | 4 / 0 | 6 / 6 |
Each cell gives comparisons / swaps. Bubble sort here stops after a pass with no swap.
11Problem
Inversions in [3, 1, 2]
How many inversions does [3, 1, 2] have?
Hint
Check the pairs (3, 1), (3, 2) and (1, 2).
Solution
Answer: 2
An inversion is a pair of values in the wrong order. (3, 1) and (3, 2) are out of order; (1, 2) is fine.
12Problem
A reversed list
How many swaps does insertion sort make on [4, 3, 2, 1]?
Hint
In [4, 3, 2, 1] every pair is out of order.
Solution
Answer: 6
A reversed list of 4 values has 4 × 3 / 2 = 6 inversions, and each swap fixes one.
13Explore
Nearly sorted
Only 3 and 4 are out of order. Insertion sort needs 6 comparisons and one swap here.
14Problem
Best for nearly sorted
Which method is the best choice for a list that is nearly sorted already?
Hint
Which counter stayed lowest on the last page?
Solution
Answer: Insertion sort
Each new value only moves a step or two, so insertion sort does close to n comparisons.
15Problem
Twice the list
A list of 1,000 values becomes 2,000 values. Roughly how does the worst-case work of insertion sort change?
Hint
The work grows like n²/2.
Solution
Answer: It goes up about four times
The work is about n²/2, and (2n)² = 4n².
16Practice
Complete bubble sort
Complete bubble sort so the program prints [1,2,4,5,8].
[1,2,4,5,8]const a = [5, 1, 4, 2, 8];
for (let pass = 0; pass < a.length - 1; pass++) {
for (let j = 0; j < a.length - 1 - pass; j++) {
// If a[j] is bigger than a[j + 1], swap them.
}
}
console.log(a);
Hint
Swap with [a[j], a[j + 1]] = [a[j + 1], a[j]]. Two plain assignments lose one value.
A solution
const a = [5, 1, 4, 2, 8];
for (let pass = 0; pass < a.length - 1; pass++) {
for (let j = 0; j < a.length - 1 - pass; j++) {
if (a[j] > a[j + 1]) {
[a[j], a[j + 1]] = [a[j + 1], a[j]];
}
}
}
console.log(a);17Practice
Count the swaps
Count the swaps bubble sort makes on [5, 1, 4, 2, 8]. The program should print 4, the number of inversions.
4const a = [5, 1, 4, 2, 8];
let swaps = 0;
// Bubble sort a, adding 1 to swaps for every swap.
console.log(swaps);
Hint
Add 1 only inside the if, where the swap happens.
A solution
const a = [5, 1, 4, 2, 8];
let swaps = 0;
for (let pass = 0; pass < a.length - 1; pass++) {
for (let j = 0; j < a.length - 1 - pass; j++) {
if (a[j] > a[j + 1]) {
[a[j], a[j + 1]] = [a[j + 1], a[j]];
swaps++;
}
}
}
console.log(swaps);18Explain
Common mistakes
const a = [5, 1, 4, 2, 8];
for (let j = 0; j < a.length - 1; j++) {
if (a[j] > a[j + 1]) [a[j], a[j + 1]] = [a[j + 1], a[j]];
}
console.log(a);[1,4,2,5,8]const a = [5, 1, 4, 2, 8];
for (let pass = 0; pass < a.length - 1; pass++) {
for (let j = 0; j < a.length - 1 - pass; j++) {
if (a[j] > a[j + 1]) [a[j], a[j + 1]] = [a[j + 1], a[j]];
}
}
console.log(a);[1,2,4,5,8]One pass only carries the largest value to the end. Bubble sort needs passes until nothing moves.
const a = [10, 9, 100, 2];
a.sort();
console.log(a);[10,100,2,9]const a = [10, 9, 100, 2];
a.sort((x, y) => x - y);
console.log(a);[2,9,10,100]Without a compare function JavaScript sorts numbers as text, so "100" comes before "2". Pass (x, y) => x - y.
19
Summary
- Bubble sort swaps neighbours; each pass carries the largest value to the end.
- Selection sort always makes n(n − 1)/2 comparisons and at most n − 1 swaps.
- Insertion sort is fast on nearly sorted lists.
- Bubble and insertion sort make one swap per inversion.
- All three take about n² steps in the worst case.