Proof Academy · Python · Journey 08

Searching and sorting

Compare linear and binary search, then trace the swaps that put a list in order.

Lab and core lesson: 45–55 minutes, plus guided study · Builds on Test, debug and refine

01 · Understand and predict

Pick an algorithm that fits the data

Linear search inspects items in sequence and works even when the list is unsorted. Stop at the first match if the brief asks for the first position. Return a clear absence value such as −1 when no match exists.

Binary search works on sorted data. Compare the target with the middle item, then keep only the side that could contain it. Start with low = 0 and high = len(values) − 1. If low becomes greater than high, no candidates remain.

Bubble sort compares neighbours and swaps pairs that are out of order. A full left-to-right pass moves the largest remaining value to its final position. Merge sort divides a list into smaller lists, then merges sorted halves by taking the smaller front item first.

values = [4, 2, 3, 1]
for i in range(len(values) - 1):
    if values[i] > values[i + 1]:
        values[i], values[i + 1] = values[i + 1], values[i]
print(values)

Worked trace

  1. Compare 4 and 2. Swap to get [2, 4, 3, 1].
  2. Compare 4 and 3. Swap to get [2, 3, 4, 1].
  3. Compare 4 and 1. Swap to get [2, 3, 1, 4]. The largest is settled, but the list still needs more passes.

Trace a shrinking search range

The first comparison is with 7 at index 2. The target is larger, so low becomes 3. The next comparison is with 10 at index 3. The code prints 3 and leaves the loop.

values = [2, 4, 7, 10, 13]
low = 0
high = len(values) - 1
target = 10
while low <= high:
    middle = (low + high) // 2
    if values[middle] == target:
        print(middle)
        break
    elif values[middle] < target:
        low = middle + 1
    else:
        high = middle - 1
Why can't binary search safely discard half of [9, 2, 7, 1, 5] after looking at 7?

From code to machine. Counting comparisons is one way to reason about algorithm cost independently of processor speed. Binary search usually compares fewer items on a long sorted list. Sorting the list first takes work, so a linear search may be preferable for one lookup in unsorted data.

Guided study

Read it, trace it, test it

Establish the contract before tracing

When the brief asks you to search a list, find out whether it wants a Boolean, a position or the matching record. These are different outputs. If a name appears twice, does the task ask for the first match or all matches? A linear search can stop at the first match. On [8, 2, 8, 4], searching for 8 returns index 0 if the function promises the first index. Searching for 4 visits four values and returns index 3. The index and the number of comparisons are different quantities.

An empty list contains no valid positions. A search should report absence without accessing position 0. -1 is a useful absence result if all successful positions are non-negative, but do not then use it as a list index without checking. In Python values[-1] selects the last item, so forgetting that guard could display a real record when no record was found.

Trace binary search on an absent target

Suppose the sorted data is [2, 4, 7, 10, 13] and the target is 8. Record the candidate interval using inclusive indices. The midpoint is (low + high) // 2, using integer division. When the middle value is below the target, move low to middle + 1. The middle has already been checked, so keeping it could prevent progress.

LowHighMiddle indexMiddle valueNew interval
04273 to 4
343103 to 2, which is empty

The target is absent. In each pass the interval shrinks. Starting with high = len(values) would sometimes allow the search to look beyond the last index. Using while low < high would skip the final candidate when low equals high. Use a one-item list as a deliberate test of both issues. On an unsorted list, the rule that everything on one side is too large or too small does not hold.

Trace two kinds of sorting

Bubble sort looks at adjacent items and swaps when the left one is greater. One pass through [5, 3, 2, 4] gives [3, 2, 4, 5]. The final 5 is settled, but the rest is not sorted yet. Repeat on the unsorted prefix. It is possible to finish early when a full pass makes no swaps. If you use a flag for this, reset it at the start of each pass and set it when you swap. Then test an already sorted list and one in reverse order.

Merge sort has a different structure. Split a list into halves until each sublist contains at most one item. Merge sorted sublists by comparing the first unmerged item on each side. For [3, 8] and [1, 5], take 1, then 3, then 5. The second sublist is empty, so append the remaining 8. Merging two sorted lists preserves order, which is what makes the method work when the small merges are combined into larger ones. Trace the split and merge of [8, 3, 5, 1] before trying to implement it.

Compare algorithms with evidence

A linear search can find the first item in one comparison, but a missing target can require inspecting every item. Binary search reduces the candidate interval each time, but the list must already be sorted. Sorting only for one lookup can cost more work than scanning once. For many lookups on stable data, the up-front sort can make sense. In your explanation name the operation you counted and the assumptions about the input.

Practise a Paper 2 change request

An inventory file stores a list of integer codes. A starter search uses while low < high with an inclusive upper bound. Test [7] with target 7, then use [2, 4, 7, 10, 13] with target 13 and 8. Change the condition and explain why your tests expose the mistake. In the sandbox, place the codes on one line and the target on the next. Use the editor's manual run for this separate binary-search task.

Check your guided practice

Use while low <= high so the last candidate is still checked. The one-item search returns 0, 13 returns 4 and 8 returns −1. Make sure the unsuccessful branches move past the middle using middle + 1 or middle - 1. Check an empty list as well. It should report −1 before trying to read an element.

02 · Run and repair

Search the final position

The code receives space-separated integers and then a target on the next line. It should print the first matching index or −1. Run it with a target in the final position.

Enter one value per line. Each input() reads the next line.

Ready to run.

Need a hint?

The stop value of range is excluded. Check which indices range(len(values)) supplies.

03 · Build independently

Put race times in order

Read one line of space-separated integer times. Implement bubble sort and print the sorted values separated by one space.

  • Print an empty line when no times are supplied. Keep duplicates.
  • Compare adjacent values and swap only when the left value is larger. Repeat enough passes to sort a list in reverse order.
  • Review your solution for a bubble-sort loop. The output checks verify the result, while the brief specifies the algorithm.

One line for input(). Leave the box empty to test a blank entry.

Ready to run.

Need a hint?

Build a list with [int(item) for item in input().split()]. Use len(times) − 1 passes. On pass p, compare neighbours up to the start of the already sorted suffix.

04 · Explain and transfer

Explain your reasoning

Why can the inner loop do one fewer comparison after each full pass?

Compare your explanation

Each pass places the largest remaining value at the end of the unsorted part. The suffix is already in its final positions, so the next pass can stop before it.

Independent follow-up. Trace merging [2, 5, 9] and [1, 3, 7] into one sorted list. Record which front item was selected on each comparison and what happens when one side is empty.

Original GCSE practice · Pearson Edexcel 1CP2 1.2.4, 1.2.6–1.2.7 and 6.1.6. Download your .py file to keep it after leaving the page.

Next: Files, CSV and persistent data →