Start free

GCSE · 7 exercises

Python sorting algorithms

Bubble sort swaps neighbours that are in the wrong order, pass after pass. Insertion sort takes each item in turn and slides it back into place among those before it. Merge sort splits the list, sorts each half and merges them.

These exercises ask for the steps, not just the result: write the algorithm yourself rather than calling sorted().

a = [5, 1, 4, 2]
for end in range(len(a) - 1, 0, -1):
    for i in range(end):
        if a[i] > a[i + 1]:
            a[i], a[i + 1] = a[i + 1], a[i]
print(a)

Watch for: Off-by-one: comparing a[i] with a[i + 1] means i must stop one before the end.

Exercises

  1. Bubble sort swapsSort the numbers with bubble sort (repeatedly swap neighbours that are in the wrongAdvanced
  2. Selection sort, step by stepSelection sort: for each position from the left, find the smallest remaining numberAdvanced
  3. Insertion sort, step by stepInsertion sort: take each number from the second one on and move it left until itAdvanced
  4. Counting inversionsAn inversion is a pair of positions i < j with a[i] > a[j].Advanced
  5. Sort by frequencySort the letters of a word by how often they appear, most frequent first; equallyAdvanced
  6. By length, then alphabetSort words by length, shortest first; words of the same length alphabeticallyAdvanced
  7. Sort by digit sumSort positive numbers by the sum of their digits; numbers with the same digit sum byAdvanced
Start with “Bubble sort swaps”