Write insertion and selection sort and know when they are the right choice.
Use it when the list is short, or nearly sorted, or a write is costly. Signal words: the list is almost in order, each item is only a few places out, the fewest writes, a short list.
Start the front of the list is empty, or the first value alone. It is sorted.
Step selection finds the smallest of the rest and swaps it to the next place. Insertion takes the next value and shifts larger values right until it fits.
Stop when the front covers the list. Selection stops after n − 1 passes, insertion after n − 1 insertions.
It does not suit a long random list: both sorts are O(n²) there, and the comparison floor is about n log n.
Cost: selection makes n(n − 1)/2 comparisons and at most n − 1 swaps. Insertion makes n − 1 comparisons plus about one for each shift, and the shifts equal the inversions: O(n + inversions).
In this lesson you write the two simple sorts, selection and insertion, and count what each one does. You learn that the right choice depends on the data. A nearly sorted list and a random list need very different amounts of work from the same code.
You work on the cinema app of a theatre chain. Every night it sorts the seat holds by expiry time, earliest first, so that staff release the oldest holds first.
On a busy night the list has 100,000 holds. New holds join the end with later times, and a few holds get their time extended, so every hold sits at most 5 places from where it belongs. Comparing two expiry times takes about 1 microsecond.
Your team lead says: The doors open in ten minutes. Pick a simple sort, and tell me how long it takes.
Here is a short test: six holds with the expiry minutes 41, 17, 29, 8, 35 and 23. Sorted, they read 8, 17, 23, 29, 35, 41.
So the task is this: sort the holds with as little work as possible, and say which simple sort fits which situation.
You hold cards in your hand, and you want them in order. One way is to pick up the cards one at a time from the table, and slide each into its place among the cards already in your hand. The cards in your hand are always in order.
The other way is to spread all the cards face up, find the smallest, and put it first in a row. Then you find the smallest of the rest and put it next. The first way is insertion sort, and the second is selection sort. The cards are the holds, and a comparison is a look at two cards.
Like sorting a hand of cards: slide each card into place among the cards in your hand, or keep taking the smallest.
Before you write code, sort the six holds by hand. It shows how many comparisons and swaps you need.
Solve it by hand: Six holds: sort them by selection. The hand-solve sheet loads in your browser.
You use the second way from the card game. You look for the smallest hold among the places that are not final, and swap it into the next place.
The holds are 41, 17, 29, 8, 35 and 23. Each pass compares every hold after the next place with the smallest so far.
| Pass | Smallest of the rest | Swap | List after the pass | Comparisons so far |
|---|---|---|---|---|
| 1 | 8 | places 0 and 3 | [8, 17, 29, 41, 35, 23] | 5 |
| 2 | 17 | none, already in place | [8, 17, 29, 41, 35, 23] | 9 |
| 3 | 23 | places 2 and 5 | [8, 17, 23, 41, 35, 29] | 12 |
| 4 | 29 | places 3 and 5 | [8, 17, 23, 29, 35, 41] | 14 |
| 5 | 35 | none, already in place | [8, 17, 23, 29, 35, 41] | 15 |
You made 15 comparisons and 3 swaps. Look at what grows. Pass 1 compares 5 values, pass 2 compares 4, and so on: n × (n − 1) / 2 comparisons in all.
Start with a correct version. It is selection sort.
def selection_sort(values):
items = list(values)
n = len(items)
for i in range(n - 1):
smallest = i
for j in range(i + 1, n): # compare every value after place i
if items[j] < items[smallest]:
smallest = j
if smallest != i:
items[i], items[smallest] = items[smallest], items[i]
return itemsThis is correct. It makes n × (n − 1) / 2 comparisons, whatever order the holds are in: O(n²). The team keeps it as the reference.
Now check the real size.
A busy night has 100,000 holds, and one comparison takes 1 microsecond. The doors open in ten minutes.
Here is the count:
So the sort would finish more than an hour after the doors open.
Predict the cost
Q A busy night has 100,000 holds, selection sort compares 4,999,950,000 pairs, and one comparison takes 1 microsecond. About how long does it take?
Answer: C
4,999,950,000 microseconds is 4,999.95 seconds. Divided by 60, that is about 83.3 minutes: far more than the ten minutes available.
The first attempt is correct, but it compares pairs that cannot matter when the list is almost in order. Now the team uses that.
Look at the holds again. Most of them are already next to the holds they belong beside. Selection looks at every pair on every pass, and it ignores that.
Insertion sort takes the first way from the card game. It keeps the front of the list in order. It takes the next hold, compares it with the hold before it, and shifts larger holds right until the hold fits. When the hold before is not larger, it stops at once.
A hold that is at most 5 places out passes at most 5 larger holds. So each hold costs at most 6 comparisons, and the whole sort costs at most about 6 × n.
Here are the eight holds 14, 9, 21, 33, 27, 40, 38 and 52, which are nearly sorted:
| Sort | Comparisons | Swaps or shifts |
|---|---|---|
| Selection | 28 | 3 swaps |
| Insertion | 9 | 3 shifts |
Insertion needs a third of the comparisons here. The gap grows with the list.
Race: Selection and insertion on the same sizes. The operation counter loads in your browser.
The race counts comparisons. At 1,000 holds, selection makes 499,500. Insertion makes 499,500 on a reversed list, but only 2,255 on a nearly sorted one. At 2,000 holds the counts are 1,999,000 against 4,648.
Insertion sort compares the next hold with the one before it, shifts larger holds right, and stops at once when none is larger.
The holds are [14, 9, 21, 33, 27, 40, 38, 52]. Insertion sort takes each hold in turn and shifts the larger holds right. The player stops at five steps and asks you to predict.
Dry run: Predict each step: eight nearly sorted holds. The step-by-step player loads in your browser.
Reading without the player? Cover the last columns and predict them row by row.
| Next hold | Sorted part before | Larger holds shifted | Comparisons so far |
|---|---|---|---|
| 9 | [14] | 1 | 1 |
| 21 | [9, 14] | 0 | 2 |
| 33 | [9, 14, 21] | 0 | 3 |
| 27 | [9, 14, 21, 33] | 1 | 5 |
| 40 | [9, 14, 21, 27, 33] | 0 | 6 |
| 38 | [9, 14, 21, 27, 33, 40] | 1 | 8 |
| 52 | [9, 14, 21, 27, 33, 38, 40] | 0 | 9 |
The sort used 9 comparisons and 3 shifts. Look at the hold 27. It passes the 33 and stops at the 21: that is two comparisons for one shift. The comparison that stops the scan is why comparisons exceed shifts.
The two sorts also differ in how much they move. Here are 1,000 holds in four orders, each counted by running the sort.
| List of 1,000 holds | Selection: comparisons | Selection: swaps | Insertion: comparisons | Insertion: shifts |
|---|---|---|---|---|
| Already sorted | 499,500 | 0 | 999 | 0 |
| Nearly sorted | 499,500 | 589 | 2,255 | 1,257 |
| Random order | 499,500 | 994 | 249,946 | 248,954 |
| Reversed | 499,500 | 500 | 499,500 | 499,500 |
The nearly sorted list shuffles each block of six sorted values, so every hold is at most 5 places out. The random list holds 1,000 seeded values from 1 to 1,000,000.
Selection never makes more than 999 swaps, because it makes at most one per pass. Insertion shifts once for every pair that is out of order, which is the number of inversions. A random list has about 250,000 of them.
The first sort is the right choice when a write is expensive. The second is the right choice when the list is nearly sorted.
Here is the rule that keeps both sorts correct. Every line of both templates exists to protect it.
The front of the list is always sorted: selection adds the smallest remaining value to it, and insertion adds the next value, shifting larger ones aside.
At the start the front is empty, or one value long, so it is sorted. Selection keeps it final: after pass i, places 0 to i hold the smallest i + 1 values in order. Insertion keeps it sorted: after the insertion at place i, places 0 to i are in order.
When the front covers the whole list, the list is sorted. Each step adds one value to the front, so a list of n values takes n − 1 steps.
Use it when the list is short, or nearly sorted, or a write is costly. Signal words: the list is almost in order, each item is only a few places out, the fewest writes, a short list.
Start: the front of the list is empty, or the first value alone. It is sorted.
Step: selection finds the smallest of the rest and swaps it to the next place. Insertion takes the next value and shifts larger values right until it fits.
Stop: when the front covers the list. Selection stops after n − 1 passes, insertion after n − 1 insertions.
It does not suit a long random list: both sorts are O(n²) there, and the comparison floor is about n log n.
Cost: selection makes n(n − 1)/2 comparisons and at most n − 1 swaps. Insertion makes n − 1 comparisons plus about one for each shift, and the shifts equal the inversions: O(n + inversions).
def selection_sort(values):
# [1] Work on a copy; the front part of it is always final.
items = list(values)
n = len(items)
# [2] For each place, find the smallest value among the places that are not final yet.
for i in range(n - 1):
smallest = i
for j in range(i + 1, n):
if items[j] < items[smallest]:
smallest = j
# [3] Swap it into place i: at most one swap for each place.
if smallest != i:
items[i], items[smallest] = items[smallest], items[i]
# [4] Every place is final: return the sorted list.
return itemspublic int[] selectionSort(int[] values) {
// [1] Work on a copy; the front part of it is always final.
int[] items = values.clone();
int n = items.length;
// [2] For each place, find the smallest value among the places that are not final yet.
for (int i = 0; i < n - 1; i++) {
int smallest = i;
for (int j = i + 1; j < n; j++) {
if (items[j] < items[smallest]) {
smallest = j;
}
}
// [3] Swap it into place i: at most one swap for each place.
if (smallest != i) {
int tmp = items[i];
items[i] = items[smallest];
items[smallest] = tmp;
}
}
// [4] Every place is final: return the sorted list.
return items;
}vector<int> selectionSort(vector<int>& values) {
// [1] Work on a copy; the front part of it is always final.
vector<int> items = values;
int n = (int)items.size();
// [2] For each place, find the smallest value among the places that are not final yet.
for (int i = 0; i < n - 1; i++) {
int smallest = i;
for (int j = i + 1; j < n; j++) {
if (items[j] < items[smallest]) {
smallest = j;
}
}
// [3] Swap it into place i: at most one swap for each place.
if (smallest != i) {
swap(items[i], items[smallest]);
}
}
// [4] Every place is final: return the sorted list.
return items;
}function selectionSort(values) {
// [1] Work on a copy; the front part of it is always final.
const items = [...values];
const n = items.length;
// [2] For each place, find the smallest value among the places that are not final yet.
for (let i = 0; i < n - 1; i++) {
let smallest = i;
for (let j = i + 1; j < n; j++) {
if (items[j] < items[smallest]) {
smallest = j;
}
}
// [3] Swap it into place i: at most one swap for each place.
if (smallest !== i) {
[items[i], items[smallest]] = [items[smallest], items[i]];
}
}
// [4] Every place is final: return the sorted list.
return items;
}Exercise · Find the bug: The smallest that is never reset. This selection sort leaves some lists unsorted. Which line is wrong?
def selection_sort(values):
items = list(values)
n = len(items)
for i in range(n - 1):
smallest = 0
for j in range(i + 1, n):
if items[j] < items[smallest]:
smallest = j
if smallest != i:
items[i], items[smallest] = items[smallest], items[i]
return itemsdef insertion_sort(values):
# [1] Work on a copy; the front part of it is always in order.
items = list(values)
# [2] Take each value in turn.
for i in range(1, len(items)):
x = items[i]
j = i - 1
# [3] Shift every larger value one place right. Equal values stay where they are.
while j >= 0 and items[j] > x:
items[j + 1] = items[j]
j -= 1
# [4] Drop the value into the gap.
items[j + 1] = x
# [5] The whole list is in order: return it.
return itemspublic int[] insertionSort(int[] values) {
// [1] Work on a copy; the front part of it is always in order.
int[] items = values.clone();
// [2] Take each value in turn.
for (int i = 1; i < items.length; i++) {
int x = items[i];
int j = i - 1;
// [3] Shift every larger value one place right. Equal values stay where they are.
while (j >= 0 && items[j] > x) {
items[j + 1] = items[j];
j--;
}
// [4] Drop the value into the gap.
items[j + 1] = x;
}
// [5] The whole list is in order: return it.
return items;
}vector<int> insertionSort(vector<int>& values) {
// [1] Work on a copy; the front part of it is always in order.
vector<int> items = values;
// [2] Take each value in turn.
for (int i = 1; i < (int)items.size(); i++) {
int x = items[i];
int j = i - 1;
// [3] Shift every larger value one place right. Equal values stay where they are.
while (j >= 0 && items[j] > x) {
items[j + 1] = items[j];
j--;
}
// [4] Drop the value into the gap.
items[j + 1] = x;
}
// [5] The whole list is in order: return it.
return items;
}function insertionSort(values) {
// [1] Work on a copy; the front part of it is always in order.
const items = [...values];
// [2] Take each value in turn.
for (let i = 1; i < items.length; i++) {
const x = items[i];
let j = i - 1;
// [3] Shift every larger value one place right. Equal values stay where they are.
while (j >= 0 && items[j] > x) {
items[j + 1] = items[j];
j--;
}
// [4] Drop the value into the gap.
items[j + 1] = x;
}
// [5] The whole list is in order: return it.
return items;
}Rebuild the template: put its lines back in order. Loads in your browser.
One selection pass scans the places that are not final, finds the smallest value, and swaps it into the next place.
Exercise · Put it in order: Add one score to the board. Arrange the lines into a function that adds a new score to a sorted leaderboard and returns the new board, still sorted.
def insert_score(board, score):
items = board + [score]
j = len(board) - 1
while j >= 0 and items[j] > score:
items[j + 1] = items[j]
j -= 1
items[j + 1] = score
return items
items[j] = items[j + 1]The two sorts have the same goal, so the question is which one fits. You can answer it before you write any code.
Then check the two ends: what do the sorts do on an empty list, and on a sorted one?
| Situation | Better simple sort | Why |
|---|---|---|
| A few dozen values | Either | The cost is small anyway |
| A nearly sorted list | Insertion | Cost grows with the inversions |
| Writes are expensive | Selection | At most n − 1 swaps |
| Equal values must keep their order | Insertion | It is stable |
A game app keeps a leaderboard of 6 scores in order: 12, 25, 33, 47, 58 and 64. A new score of 40 arrives. The board must stay sorted.
The board is already sorted, so one step of insertion is enough. Only the new value is out of place.
| Step | j | Value at j | Larger than 40? | What happens |
|---|---|---|---|---|
| 1 | 5 | 64 | yes | shift 64 right |
| 2 | 4 | 58 | yes | shift 58 right |
| 3 | 3 | 47 | yes | shift 47 right |
| 4 | 2 | 33 | no | stop, and put 40 at place 3 |
The new board is 12, 25, 33, 40, 47, 58 and 64. It took 4 comparisons and 3 shifts.
Real data brings edge cases.
For values = [] or values = [5], there is nothing to put in order. Selection makes no pass, since range(n - 1) is empty. Insertion makes no insertion, since range(1, n) is empty. Both return the list unchanged.
For values = [7, 7, 7, 7], selection still makes 6 comparisons but no swap, because each smallest value is already in its place. Insertion makes 3 comparisons and no shifts, because no value is strictly larger than the one after it.
For values = [1, 2, 3, 4, 5, 6], insertion makes 5 comparisons and no shifts, which is n − 1. Selection makes 15 comparisons, because it looks at every pair whatever the order.
For values = [6, 5, 4, 3, 2, 1], insertion makes 15 comparisons and 15 shifts, which is the most it can make. Selection makes 15 comparisons and only 3 swaps. A reversed list is the worst case for insertion's shifts, while selection still swaps only 3 times.
This version writes items[j] >= x in the shifting loop. A value then moves in front of an equal value, and equal values change order.
Counterexample: take the pairs (2, a), (2, b) and (1, c), compared by their first number only. The version returns (1, c), (2, b), (2, a): the equal pair has swapped. The correct strict comparison returns (1, c), (2, a), (2, b).
The fix is a strict >. Stability costs nothing here, and later lessons need it.
This version writes while j > 0 and items[j] > x, as if place 0 needed no check. A value that belongs before place 0 never passes it.
Counterexample: values = [3, 1, 2]. At i = 1 the value is 1 and j is 0, so the loop does not run, and 1 stays at place 1. The version returns [3, 1, 2], unchanged.
The fix is j >= 0. Place 0 is a real place.
Stopping the scan at j above zero never compares with place zero, so a value that belongs first never gets there.
This version swaps items[i] with items[j] every time it finds a smaller value, instead of remembering the place and swapping once. It sorts correctly, but it is not selection sort, and it loses the limit of n − 1 swaps.
Counterexample: on the reversed list [5, 4, 3, 2, 1] it makes 10 swaps, and selection makes 2. On a reversed list of 1,000 values it makes 499,500 swaps, and selection makes 500.
Remember the smallest place in the inner loop, and swap once after it.
This version uses selection sort for the night list because "simple sorts are fine for simple data". The data is almost sorted, but selection does not care.
Counterexample: for the 100,000 nearly sorted holds, selection makes 4,999,950,000 comparisons, which is about 83 minutes. Insertion makes 225,063, which is about 0.23 seconds, so it is 22,216 times fewer.
Choose by the data and by the cost that matters, not by the name.
Exercise · Break it: Find the list this sort leaves unsorted. This insertion sort uses an if where the template has a while. Find a list it sorts wrongly.
def insertion_sort(values):
items = list(values)
for i in range(1, len(items)):
x = items[i]
j = i - 1
if j >= 0 and items[j] > x:
items[j + 1] = items[j]
j -= 1
items[j + 1] = x
return itemsThe app also sorts 10,000 random bookings. The list has no order to use. Insertion makes 24,825,638 comparisons and 24,815,649 shifts on one seeded random list of values from 1 to 1,000,000.
The comparison floor for 10,000 items, from the first lesson, is 118,459. Insertion makes about 210 times as many. A simple sort is the wrong tool here: the next lessons build sorts that come close to the floor.
Your team lead brings four product changes. Each one asks which cost matters.
A log collector receives lines almost in time order, each at most 5 places out. Insertion sort costs at most 6 comparisons for each line. The same idea works on a linked list (LeetCode 147: Insertion Sort List).
A banner shows the 20 oldest tickets of 100,000. Stop selection sort after 20 passes. That costs at most 20 × n comparisons, and the rest of the list is never sorted.
Parcels on a belt must be put in order with swaps of any two places. Selection sort makes at most n − 1 swaps. The exact fewest is n minus the number of cycles of the arrangement.
A statement list sorted by time must keep entries with the same time in their posted order. Use insertion with a strict comparison. Selection with swaps is not stable. On (2, a), (2, b) and (1, c), its first pass swaps (1, c) with (2, a), and the result is (1, c), (2, b), (2, a).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how insertion sort works and when you would choose it over selection sort. Then say what each costs on a sorted list. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
Both sorts keep the front of the list sorted. Selection finds the smallest of the rest and swaps it into the next place. Insertion takes the next value and shifts larger values right until it fits.
Selection always makes n(n − 1)/2 comparisons and at most n − 1 swaps. Insertion makes n − 1 comparisons on a sorted list, and one shift for every pair out of order.
So insertion fits short and nearly sorted lists, and selection fits when writes are costly. A long random list needs a faster sort.
Both simple sorts keep the front of the list sorted, and each step adds one value to it. The straightforward choice costs about n squared over 2 comparisons, so I choose by the data.
Selection sort finds the smallest of the rest and swaps it into the next place. It makes the same comparisons on every input, but at most n minus 1 swaps, so it suits storage where a write is costly.
Insertion sort takes the next value and shifts larger values right until it fits. It makes n minus 1 comparisons on a sorted list, and one shift for each pair out of order. On a list where every item is a few places out, it is nearly linear.
A long random list needs about n squared over 4 shifts, so I use a faster sort there. I also use a strict comparison, so equal values keep their order.
Checkpoint · Selection sort
Q1/3 What does one pass of selection sort do?
Answer: B
Selection sort fixes one place per pass: after pass i, places 0 to i hold the smallest i + 1 values in order.
Q2/3 How many comparisons does selection sort make on 1,000 values?
Answer: C
Each pass compares every value after the next place, so the count is n × (n − 1) / 2 for any input. It does not depend on the order.
Q3/3 Selection sort sorts a list of 1,000 values. At most how many swaps does it make?
Answer: C
A pass makes at most one swap, and there are n − 1 passes, so at most 999 swaps.
Checkpoint · Insertion sort
Q1/3 What does insertion sort do with the next value?
Answer: B
The front part is kept sorted. The next value moves left past every larger value, and the larger values shift right to make room.
Q2/3 For 1,000 values already in order, how many comparisons and shifts does insertion sort make?
Answer: B
Each value is compared once with the value before it, which is not larger, so the scan stops at once. That makes n − 1 comparisons and no shifts.
Q3/3 What do the shifts of insertion sort count?
Answer: B
Each shift removes exactly one inversion. A list with few inversions, such as a nearly sorted one, needs few shifts.
Checkpoint · Choosing a sort
Q1/2 The night list of 100,000 holds is nearly sorted, and every hold is at most 5 places out. Which sort should the app use?
Answer: B
Insertion costs at most 6 comparisons per hold here, and 225,063 in all. Selection makes 4,999,950,000 comparisons on any input.
Q2/2 Which simple sort is stable, so that equal values keep their order?
Answer: B
A strict comparison never moves a value past an equal one. Swapping in selection sort can carry a value past an equal one.
Checkpoint · Mistakes
Q1/2 An insertion sort is written with while j > 0 and items[j] > x. What goes wrong?
Answer: B
Place 0 is never compared, so a smaller value cannot move in front of it. The test must be j >= 0.
Q2/2 A device writes slowly but reads and compares quickly, and the list is in random order. Which simple sort makes the fewest writes?
Answer: B
On a random list of 1,000 values, insertion makes about 249,000 shifts, and selection makes at most 999 swaps.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Selection by hand on ticket ages | Platform | Easy | k selection passes fix the first k places |
| 2 | Insertion for nearly sorted logs | Observe | Easy | Insertion from the sorted end on a chain |
| 3 | Bubble pass count | Bank | Easy | Each sweep moves a value one place |
| 4 | Sort a short list in place | Shop | Easy | Hand sort or library sort, by size |
| 5 | Fewest swaps to sort a permutation | Freight | Medium | Selection with swaps counted, as cycles |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.