Sorting
Selection Sort
Selection sort treats the list as two parts: a sorted part on the left, initially empty, and an unsorted part on the right. In each pass it selects the smallest element of the unsorted part and swaps it with the leftmost unsorted element, so the sorted part grows by one. After n − 1 passes the list is sorted. Each pass makes at most one swap, so selection sort does at most n − 1 swaps in all — far fewer than bubble sort can — but it still scans the whole unsorted part every time, whatever the input looks like.
Worked example on [29, 10, 14, 37, 13]. Pass 1: the smallest is 10; swap it with 29 → [10, 29, 14, 37, 13]. Pass 2: the smallest of [29, 14, 37, 13] is 13; swap it with 29 → [10, 13, 14, 37, 29]. Pass 3: 14 is already the smallest of what remains, so it swaps with itself. Pass 4: swap 37 and 29 → [10, 13, 14, 29, 37].
Selection sort treats the list as two parts: a sorted part on the left, initially empty, and an unsorted part on the right. In each pass it selects the smallest element of the unsorted part…
Insertion Sort
Insertion sort is how many people sort a hand of cards. The first element on its own is a sorted part. Each later element is taken in turn and inserted into its correct place in the sorted part on its left: elements of the sorted part larger than it are shifted one place right, and it drops into the gap. After the element at index i has been inserted, the first i + 1 elements are in order — but, unlike selection sort, they are not yet in their final positions, because smaller elements may still arrive from the right.
Worked example on [7, 3, 5, 1]. Insert 3: it is smaller than 7, so 7 shifts right → [3, 7, 5, 1]. Insert 5: 7 shifts right, 3 does not → [3, 5, 7, 1]. Insert 1: 7, 5 and 3 all shift → [1, 3, 5, 7]. On a list that is already sorted, each new element is compared once and never moved, so insertion sort finishes in a single sweep of n − 1 comparisons.
- Compares adjacent elements, swaps
- Largest reaches the right end
- n(n − 1)/2 comparisons
- Selects smallest of unsorted part
- Smallest reaches the left end
- At most one swap per pass
- Inserts each element into sorted part
- First two in order; nothing else moved
- Sorted list: n − 1 comparisons
Insertion sort is how many people sort a hand of cards. The first element on its own is a sorted part. Each later element is taken in turn and inserted into its correct place in the sorted…
Time Complexity
Time complexity describes how the number of basic steps an algorithm takes grows as the input size n grows, ignoring the speed of a particular machine. The book uses three simple rules. An algorithm with no loop, doing a fixed amount of work, has constant time complexity. One with a single loop running from 1 to n has linear complexity, proportional to n. One with a loop inside a loop, each running up to n, has quadratic complexity, proportional to n². Bubble, selection and insertion sort are all built from nested loops, so all three are quadratic: doubling the list roughly quadruples the work in the worst case.
Time complexity describes how the number of basic steps an algorithm takes grows as the input size n grows, ignoring the speed of a particular machine. The book uses three simple rules. An…
Worked Traces: Counting Passes, Comparisons and Swaps
Trace selection sort on [64, 25, 12, 22, 11]. In each pass it finds the smallest remaining element and swaps it into place: after pass 1 the list is [11, 25, 12, 22, 64], after pass 2 it is [11, 12, 25, 22, 64], after pass 3 it is [11, 12, 22, 25, 64], and pass 4 changes nothing. Bubble sort on [5, 1, 4, 2, 8] without an early exit makes 4 + 3 + 2 + 1 = 10 comparisons and exactly 4 swaps, because the number of swaps equals the number of out-of-order pairs (inversions): (5,1), (5,4), (5,2) and (4,2). Insertion sort on [7, 3, 5, 1] gives [3, 7, 5, 1], then [3, 5, 7, 1], then [1, 3, 5, 7].
For n elements, a full bubble sort makes n(n − 1)/2 comparisons whatever the order of the data, which is 45 for 10 elements. Insertion sort is quickest on data that is nearly sorted, because each new element moves only a short way. Selection sort always makes about n(n − 1)/2 comparisons but at most n − 1 swaps, which matters when swapping is costly. All three take time proportional to n² in the worst case, which is why larger data sets use faster methods.
Trace selection sort on [64, 25, 12, 22, 11]. In each pass it finds the smallest remaining element and swaps it into place: after pass 1 the list is [11, 25, 12, 22, 64], after pass 2 it is…
Key takeaways
- Bubble sort swaps adjacent out-of-order pairs; each pass carries the largest remaining element to the end, and n elements need n − 1 passes.
- Without an early exit, bubble sort makes n(n − 1)/2 comparisons — 10 for five elements.
- Selection sort picks the smallest unsorted element and swaps it to the front of the unsorted part: at most one swap per pass.
- Insertion sort inserts each element into the sorted part on its left, shifting larger ones right; on sorted input it needs only n − 1 comparisons.
- No loop means constant time, one loop linear, nested loops quadratic; all three sorts are quadratic, proportional to n².
Practice questions (24)
Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.
The list [5, 1, 4, 2, 8] is sorted in ascending order by bubble sort. What does the list look like after the first pass?
Show answer
Answer: C — [1, 4, 2, 5, 8]
Comparing neighbours: 5 and 1 swap, 5 and 4 swap, 5 and 2 swap, and 5 and 8 stay, so 5 travels to just before 8 and the list is [1, 4, 2, 5, 8]. [1, 5, 4, 2, 8] stops after the first comparison, and [1, 4, 5, 2, 8] after the second. The fully sorted list needs a second pass to move 2 past 4.Selection sort is applied to [29, 10, 14, 37, 13] to arrange it in ascending order. What is the list after the second pass?
Show answer
Answer: A — [10, 13, 14, 37, 29]
Pass 1 swaps the smallest, 10, with 29: [10, 29, 14, 37, 13]. Pass 2 finds the smallest of the remaining four, 13, and swaps it with 29: [10, 13, 14, 37, 29]. [10, 29, 14, 37, 13] is the state after one pass only. [10, 14, 29, 37, 13] inserts instead of swapping, which is insertion sort, and the fully sorted list needs four passes.Insertion sort is applied to [7, 3, 5, 1] in ascending order. What is the list after the elements 3 and 5 have each been inserted?
Show answer
Answer: D — [3, 5, 7, 1]
Inserting 3 shifts 7 right: [3, 7, 5, 1]. Inserting 5 shifts 7 right again but not 3: [3, 5, 7, 1]. The 1 has not been reached yet, so it stays at the end. [3, 7, 5, 1] is the list after only one insertion, and [1, 3, 7, 5] moves the smallest element to the front first, which is what selection sort does.
Show the other 21 questions
Bubble sort, without any early-exit check, is run on a list of 5 elements. How many comparisons does it make in total?
Show answer
Answer: C — 10
There are four passes, and each compares one pair fewer than the last because another element has settled at the end: 4 + 3 + 2 + 1 = 10, which is n(n − 1)/2 with n = 5. 25 is n², the order of growth rather than the exact count. 20 assumes every pass makes four comparisons, and 4 counts the passes instead of the comparisons.What is the output of the following code?
L = [4, 2, 6, 1]n = len(L)for i in range(n - 1):for j in range(n - 1 - i):if L[j] < L[j + 1]:L[j], L[j + 1] = L[j + 1], L[j]print(L)Show answer
Answer: B — `[6, 4, 2, 1]`
This is the bubble sort loop with the comparison reversed: a pair is swapped when the left element is smaller, so smaller values sink to the end and the list ends in descending order, [6, 4, 2, 1]. The ascending answer is the trap for anyone who recognises the loop shape without reading the < sign. [4, 6, 2, 1] is the list after the first pass only.An algorithm has a loop nested inside another loop, and each loop runs up to n times. According to the textbook's classification, its time complexity is:
Show answer
Answer: D — Quadratic, proportional to n²
For each of the n runs of the outer loop the inner loop runs up to n times, so the steps multiply to about n × n — quadratic, the class of all three sorting algorithms here. The 2n option adds the loops instead of multiplying them, which would be right only if they ran one after the other. Linear is a single loop, and constant has no loop at all.In which of these sorting algorithms does each pass perform at most one swap?
Show answer
Answer: B — Selection sort
Selection sort scans the unsorted part to find its smallest element and only then makes a single swap to put it in place, so each pass costs at most one swap. Bubble sort can swap at every comparison in a pass, as the first pass on [5, 1, 4, 2, 8] does three times. Insertion sort shifts several elements to open a gap, so it is not limited to one move either.Assertion (A): After k passes of bubble sort in ascending order, the last k elements of the list are in their final positions. Reason (R): Each pass of bubble sort carries the largest element of the unsorted part to the end of that part.
Show answer
Answer: A — Both A and R are true, and R is the correct explanation of A
Because every adjacent swap moves the larger value right, the largest unsorted value is pushed all the way to the end of the unsorted part in each pass; after k passes the k largest values occupy the last k places, and no later pass moves them. R states the mechanism that produces A, so it explains it. Calling A false would confuse bubble sort with insertion sort, whose sorted part is not yet final.Bubble sort works by repeatedly:
Show answer
Answer: A — Comparing adjacent elements and swapping them if they are in the wrong order
Bubble sort swaps adjacent out-of-order pairs. Selecting the minimum describes selection sort and inserting into a sorted part describes insertion sort.Selection sort in each pass:
Show answer
Answer: A — Selects the smallest remaining element and swaps it into place
Selection sort picks the minimum of the unsorted part and places it at its position. Adjacent swapping is bubble sort.Insertion sort is similar to the way a person:
Show answer
Answer: A — Arranges playing cards in the hand
Each new card is inserted into its correct place among those already sorted. Halving a phone book is binary search.The worst-case number of comparisons in bubble sort grows roughly as:
Show answer
Answer: A — n squared
Two nested loops each run about n times, so comparisons grow as n squared. A linear growth would need a single loop.What is the output of the following code?
L = [64, 25, 12, 22, 11]m = L.index(min(L))L[0], L[m] = L[m], L[0]print(L)Show answer
Answer: A — [11, 25, 12, 22, 64]
The minimum 11 swaps with the first element 64, which is the first pass of selection sort, giving [11, 25, 12, 22, 64]. "[11, 12, 22, 25, 64]" shows the fully sorted list.What is the output of the following code?
L = [5, 1, 4, 2]for p in range(2):for j in range(len(L) - 1 - p):if L[j] > L[j + 1]:L[j], L[j + 1] = L[j + 1], L[j]print(L)Show answer
Answer: B — [1, 2, 4, 5]
After the first pass the list is [1, 4, 2, 5] and after the second it is [1, 2, 4, 5]. "[1, 4, 2, 5]" stops after one pass.What is the output of the following code?
L = [3, 2, 1]swaps = 0for i in range(len(L) - 1):for j in range(len(L) - 1 - i):if L[j] > L[j + 1]:L[j], L[j + 1] = L[j + 1], L[j]swaps += 1print(swaps)Show answer
Answer: B — 3
A reversed list of three needs a swap for each inversion: 3 swaps in all. 2 assumes one swap per pass and 6 counts comparisons wrongly.Assertion (A): Insertion sort performs well on a list that is already nearly sorted.
Reason (R): Few elements need to be shifted, so each insertion takes very few steps.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
Little shifting is required when elements are near their places, as R states. Option 2 is wrong.Consider the following statements:
A. Bubble sort repeatedly swaps adjacent elements that are out of order.
B. Selection sort makes at most one swap per pass.
C. Insertion sort always needs n squared comparisons.
D. All three have a worst-case time of order n squared.
Choose the correct answer:Show answer
Answer: A — A, B and D only
A, B and D are correct. C is false because insertion sort needs only about n comparisons on an already sorted list, so option 4 is the trap.Without any early-exit check, bubble sort on 6 elements makes how many comparisons in total?
Show answer
Answer: A — 15
The passes make 5 + 4 + 3 + 2 + 1 = 15 comparisons. 30 and 36 use n times n-1 or n squared, which overcounts.What is the output of the following code?
L = [4, 3, 2]shifts = 0for i in range(1, len(L)):key = L[i]j = i - 1while j >= 0 and L[j] > key:L[j + 1] = L[j]j -= 1shifts += 1L[j + 1] = keyprint(L, shifts)Show answer
Answer: B — [2, 3, 4] 3
Inserting 3 shifts 4 once, and inserting 2 shifts 4 and 3, so three shifts sort the list: [2, 3, 4] 3. "[2, 3, 4] 2" undercounts the shifts.What is the output of the following code?
L = [2, 9, 4]for i in range(len(L) - 1):for j in range(len(L) - 1 - i):if L[j] < L[j + 1]:L[j], L[j + 1] = L[j + 1], L[j]print(L)Show answer
Answer: B — [9, 4, 2]
Reversing the comparison to < sorts the list in descending order, giving [9, 4, 2]. "[2, 4, 9]" is ascending, and "[9, 2, 4]" stops after one pass.For a small, nearly sorted list, which of the following sorts is usually the most efficient?
Show answer
Answer: A — Insertion sort
Insertion sort does very little work when the list is almost in order. Selection sort always makes about n squared comparisons.What is the output of the following code?
L = [3, 1, 2]count = 0for i in range(len(L) - 1):m = ifor j in range(i + 1, len(L)):if L[j] < L[m]:m = jif m != i:L[i], L[m] = L[m], L[i]count += 1print(L, count)Show answer
Answer: A — [1, 2, 3] 2
Pass 0 swaps 3 with 1 and pass 1 swaps 3 with 2, so two swaps give [1, 2, 3] 2. "[1, 2, 3] 3" counts a swap for each pass including the unnecessary one.What is the output of the following code?
L = [3, 1, 2]M = sorted(L)L.sort(reverse=True)print(L, M)Show answer
Answer: A — [3, 2, 1] [1, 2, 3]
sort() sorts the list in place in descending order, while sorted() returns a new ascending list, giving [3, 2, 1] [1, 2, 3]. "[3, 1, 2] [1, 2, 3]" assumes L is unchanged.Assertion (A): Bubble sort can be made faster by stopping when a pass makes no swaps.
Reason (R): If no swaps occur in a pass, the list is already sorted and further passes are unnecessary.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
No swaps in a pass means the order is complete, which justifies stopping, as R states. Option 2 is wrong.