Sorting

A dictionary is useful because its words are in alphabetical order; the same words in random order would be almost impossible to search. Sorting — arranging elements in ascending or descending order, numerically or alphabetically — is what makes fast searching, ranking and reporting possible. This chapter works through the three sorting algorithms of the syllabus, bubble, selection and insertion sort, showing exactly how the list looks after each pass, and then how their running time grows with the size of the list. The paper sets "the list after the second pass" questions for all three, so practise the passes on paper until they are automatic.
Overview

Bubble Sort

1 min read · 2 parts

Bubble sort repeatedly steps through the list comparing adjacent elements and swapping any pair that is out of order. In one pass, the largest element still in the unsorted part is carried along to the end — it "bubbles up" — so after pass 1 the largest is last, after pass 2 the two largest are in place, and so on. A list of n elements needs n − 1 passes, and pass k (counting from 1) makes n − k comparisons, since the last k − 1 elements are already settled. The total is (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 comparisons: 10 for five elements.

Pass 1 of bubble sort on [5, 1, 4, 2, 8], ascending
CompareActionList after
5 and 1swap[1, 5, 4, 2, 8]
5 and 4swap[1, 4, 5, 2, 8]
5 and 2swap[1, 4, 2, 5, 8]
5 and 8no swap[1, 4, 2, 5, 8]

In Python the book's version is two nested loops; changing > to < sorts in descending order instead:
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]
A common refinement keeps a flag recording whether a pass made any swap and stops as soon as one makes none — on an already sorted list that stops after a single pass.

Bubble sort repeatedly steps through the list comparing adjacent elements and swapping any pair that is out of order. In one pass, the largest element still in the unsorted part is carried…

Selection Sort

1 min read · 1 part

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

1 min read · 3 parts

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.

🧠 Tell the three apart after one pass
Bubble: the largest has reached the right end. Selection: the smallest has reached the left end, by one swap. Insertion: the first two elements are in order with each other, and nothing to their right has moved.
Three sorts, side by side
Bubble sort
  • Compares adjacent elements, swaps
  • Largest reaches the right end
  • n(n − 1)/2 comparisons
Selection sort
  • Selects smallest of unsorted part
  • Smallest reaches the left end
  • At most one swap per pass
Insertion sort
  • Inserts each element into sorted part
  • First two in order; nothing else moved
  • Sorted list: n − 1 comparisons
What each sort has done after one pass.

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

1 min read · 1 part

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

1 min read

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.

  1. 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?

    1. [1, 5, 4, 2, 8]
    2. [1, 2, 4, 5, 8]
    3. [1, 4, 2, 5, 8]
    4. [1, 4, 5, 2, 8]
    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.
  2. Selection sort is applied to [29, 10, 14, 37, 13] to arrange it in ascending order. What is the list after the second pass?

    1. [10, 13, 14, 37, 29]
    2. [10, 14, 29, 37, 13]
    3. [10, 13, 14, 29, 37]
    4. [10, 29, 14, 37, 13]
    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.
  3. 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?

    1. [1, 3, 5, 7]
    2. [3, 7, 5, 1]
    3. [1, 3, 7, 5]
    4. [3, 5, 7, 1]
    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
  1. Bubble sort, without any early-exit check, is run on a list of 5 elements. How many comparisons does it make in total?

    1. 25
    2. 20
    3. 10
    4. 4
    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.
  2. 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)

    1. [1, 2, 4, 6]
    2. [6, 4, 2, 1]
    3. [4, 6, 2, 1]
    4. [2, 4, 1, 6]
    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.
  3. 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:

    1. Constant
    2. Linear, proportional to n
    3. Proportional to 2n, since there are two loops
    4. Quadratic, proportional to n²
    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.
  4. In which of these sorting algorithms does each pass perform at most one swap?

    1. Bubble sort
    2. Selection sort
    3. Insertion sort
    4. All three of them equally
    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.
  5. 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.

    1. Both A and R are true, and R is the correct explanation of A
    2. Both A and R are true, but R is not the correct explanation of A
    3. A is true, but R is false
    4. A is false, but R is true
    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.
  6. Bubble sort works by repeatedly:

    1. Comparing adjacent elements and swapping them if they are in the wrong order
    2. Selecting the smallest element and placing it first
    3. Inserting each element into a sorted part
    4. Splitting the list in halves
    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.
  7. Selection sort in each pass:

    1. Selects the smallest remaining element and swaps it into place
    2. Swaps all adjacent pairs
    3. Shifts elements to insert a key
    4. Halves the list
    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.
  8. Insertion sort is similar to the way a person:

    1. Arranges playing cards in the hand
    2. Searches a phone book by halving
    3. Stacks plates
    4. Queues at a counter
    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.
  9. The worst-case number of comparisons in bubble sort grows roughly as:

    1. n squared
    2. n
    3. log n
    4. a constant
    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.
  10. 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)

    1. [11, 25, 12, 22, 64]
    2. [11, 12, 22, 25, 64]
    3. [25, 12, 22, 11, 64]
    4. [64, 25, 12, 22, 11]
    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.
  11. 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)

    1. [1, 4, 2, 5]
    2. [1, 2, 4, 5]
    3. [5, 4, 2, 1]
    4. [2, 1, 4, 5]
    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.
  12. What is the output of the following code?
    L = [3, 2, 1]
    swaps = 0
    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]
    swaps += 1
    print(swaps)

    1. 2
    2. 3
    3. 6
    4. 1
    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.
  13. 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:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    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.
  14. 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:

    1. A, B and D only
    2. A and C only
    3. B, C and D only
    4. A, B, C and D
    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.
  15. Without any early-exit check, bubble sort on 6 elements makes how many comparisons in total?

    1. 15
    2. 30
    3. 36
    4. 21
    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.
  16. What is the output of the following code?
    L = [4, 3, 2]
    shifts = 0
    for i in range(1, len(L)):
    key = L[i]
    j = i - 1
    while j >= 0 and L[j] > key:
    L[j + 1] = L[j]
    j -= 1
    shifts += 1
    L[j + 1] = key
    print(L, shifts)

    1. [2, 3, 4] 2
    2. [2, 3, 4] 3
    3. [4, 3, 2] 0
    4. [2, 3, 4] 1
    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.
  17. 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)

    1. [2, 4, 9]
    2. [9, 4, 2]
    3. [9, 2, 4]
    4. [4, 9, 2]
    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.
  18. For a small, nearly sorted list, which of the following sorts is usually the most efficient?

    1. Insertion sort
    2. Selection sort
    3. Bubble sort without any early exit
    4. Random shuffling
    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.
  19. What is the output of the following code?
    L = [3, 1, 2]
    count = 0
    for i in range(len(L) - 1):
    m = i
    for j in range(i + 1, len(L)):
    if L[j] < L[m]:
    m = j
    if m != i:
    L[i], L[m] = L[m], L[i]
    count += 1
    print(L, count)

    1. [1, 2, 3] 2
    2. [1, 2, 3] 3
    3. [1, 3, 2] 1
    4. [1, 2, 3] 0
    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.
  20. What is the output of the following code?
    L = [3, 1, 2]
    M = sorted(L)
    L.sort(reverse=True)
    print(L, M)

    1. [3, 2, 1] [1, 2, 3]
    2. [1, 2, 3] [3, 2, 1]
    3. [3, 1, 2] [1, 2, 3]
    4. [1, 2, 3] [1, 2, 3]
    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.
  21. 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:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    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.