Home / GCSE · Edexcel / Computer Science / Computational thinking

CPX4Searching, Sorting and Efficiency

Edexcel 1CP2 · 1.2.6

A more efficient linear search on sorted data

If the list is in ascending order, a linear search can stop early: once the current item is bigger than the target, the target can't be further along.

  • Add a second Boolean flag, often called passed. It becomes True when the current item is greater than the target.
  • The loop carries on only while the target is not found and not passed and there are items left.
  • This saves compares when the target is missing: there is no need to check the rest of the list.
  • It only works on sorted data. On an unsorted list, a bigger item tells you nothing about the items after it.
Lines 14 to 20 are the search. Lines 17 and 18 stop it once the target has been passed.
 1  # -------------------------------------------
 2  # Global variables
 3  # -------------------------------------------
 4  plotNumbers = [104, 112, 118, 125, 131, 140, 147, 156]
 5  target = 0
 6  index = 0
 7  found = False
 8  passed = False
 9  
10  # -------------------------------------------
11  # Main program
12  # -------------------------------------------
13  target = int (input ("Plot number: "))
14  while ((found == False) and (passed == False) and (index < len (plotNumbers))):
15      if (plotNumbers[index] == target):
16          found = True
17      elif (plotNumbers[index] > target):
18          passed = True
19      else:
20          index = index + 1
21  
22  if (found == True):
23      print ("Plot is on the list")
24  else:
25      print ("Plot is not on the list")
Worked exampleThe user enters 121. How many items are compared with the target?
  1. 104, 112 and 118 are less than 121, so the search moves onnot found, not passed
  2. 125 is greater than 121, so passed becomes True and the loop ends121 can't be after 125 in a sorted list
4 items. Without the passed check, all 8 would be compared.
Passed flag
A Boolean set to True when the current item is greater than the target, so a search of a sorted list can stop early.
Edexcel 1CP2 · 1.2.6

Tracing a binary search in a table

Pearson asks you to trace a binary search in a table with these columns. Show the calculation of each mid-point, not just its value.

  • This table is the search for 42. Item 4 is 23, which is less than 42, so the lower half (indexes 0 to 4) goes and start becomes 5.
  • Item 7 is 42: found after only two compares. A linear search would have needed eight.
  • “Lower” means the lower half is discarded (the middle item was too small). “Higher” means the higher half is discarded (the middle item was too big).
Index[0][1][2][3][4][5][6][7][8][9]
Value381419233136424755
Start indexEnd indexCalculation of mid-pointFound Y or NDiscard lower, higher or none
09(0 + 9) // 2 = 4Nlower
59(5 + 9) // 2 = 7Ynone
Worked exampleTrace a binary search for 20 in the same list (20 isn't there).
  1. 0, 9, (0 + 9) // 2 = 4, N, higher23 > 20, so end = 3
  2. 0, 3, (0 + 3) // 2 = 1, N, lower8 < 20, so start = 2
  3. 2, 3, (2 + 3) // 2 = 2, N, lower14 < 20, so start = 3
  4. 3, 3, (3 + 3) // 2 = 3, N, lower19 < 20, so start = 4
Start (4) is now greater than end (3): no items are left, so 20 is not in the list. That took 4 compares.
Exam tipCommon slips in the trace: not updating start or end, keeping the mid-point, and stopping too soon. Keep going until the target is found or start passes end.
Edexcel 1CP2 · 1.2.6

Bubble sort

A bubble sort makes passes through a list. In each pass it compares each pair of neighbouring items and swaps them if they are in the wrong order.

  • A pass compares items 0 and 1, then 1 and 2, and so on to the end: a list of n items has n − 1 compares per pass.
  • After pass 1 (ascending order), the largest item is in its final place. After each pass, one more item is in place.
  • The sort stops after a pass with no swaps: nothing was out of order, so the list is sorted. That last pass still counts as a pass.
  • A swap uses a temporary variable, so one value isn't overwritten before it has been copied.
  • You need to trace a bubble sort by hand. You don't have to write the code for one.

Pass 1 on 7, 3, 9, 2, 5: the largest item moves to the end

Worked exampleBubble sort 7, 3, 9, 2, 5 into ascending order. Give the list after each pass.
  1. Pass 1: 3, 7, 2, 5, 93 swaps
  2. Pass 2: 3, 2, 5, 7, 92 swaps
  3. Pass 3: 2, 3, 5, 7, 91 swap
  4. Pass 4: 2, 3, 5, 7, 9no swaps, so stop
4 passes, 16 compares (4 per pass) and 6 swaps.
Bubble sort
A sort that makes passes through a list, comparing neighbouring items and swapping them if they are out of order, until a pass makes no swaps.
Pass
One run through the list, comparing each pair of neighbours once.
Swap
Exchanging the positions of two items.
Edexcel 1CP2 · 1.2.6

Merge sort

A merge sort splits a list in half again and again until every list holds one item, then merges pairs of lists back together in order until one sorted list is left.

  • A list of one item is already sorted, which is why the splitting stops there.
  • To merge two sorted lists, compare the front items, move the smaller one to the new list, and repeat. When one list is empty, copy the rest of the other.
  • Merging and sorting happen together: each merge produces a list that is in order.
  • If a list has an odd number of items, one half gets one more than the other.
  • You need to trace a merge sort by hand. In Paper 2 you may be asked to write code that merges two sorted lists (that is in the Python lists topic).

Split to single items, then merge in order

Worked exampleMerge the sorted lists 9, 26, 41 and 3, 15, 18, 33.
  1. Fronts 9 and 3: take 3. Then 9 and 15: take 9always take the smaller front item
  2. 26 and 15: take 15. 26 and 18: take 18. 26 and 33: take 26the new list grows in order
  3. 41 and 33: take 33. The second list is empty, so copy 41nothing left to compare
3, 9, 15, 18, 26, 33, 41
Exam tipShow every row of the splitting and every row of the merging. A common mistake is to merge two lists by just joining them end to end: each merge must put the items in order.
Merge sort
A sort that splits a list into single items, then repeatedly merges pairs of lists in order until one sorted list remains.
Merge
Combining two sorted lists into one sorted list by repeatedly taking the smaller front item.
Edexcel 1CP2 · 1.2.6

Divide and conquer

Divide and conquer means solving a problem by breaking it into smaller parts of the same kind, dealing with each part, and (if needed) combining the results.

AlgorithmDivide and conquer?Why
Binary searchYesEach compare halves the part of the list still to be searched
Merge sortYesIt splits the list into smaller lists, sorts them by merging and combines the results
Linear searchNoIt checks one item after another
Bubble sortNoIt works through the whole list, pass after pass
Exam tipIn 2024, many students thought linear search was divide and conquer, or named merge sort as a sort that isn't. Learn the table: binary search and merge sort are; linear search and bubble sort are not.
Divide and conquer
Solving a problem by repeatedly breaking it into smaller problems of the same type, then combining the results.
Edexcel 1CP2 · 1.2.7

Efficiency: compares, passes and memory

Pearson measures how efficient an algorithm is by the number of compares, the number of passes through a loop and the use of memory. Fewer compares and passes means less processing time.

  • Memory: bubble sort is an in-place sort: it rearranges items inside the original list and needs only one extra variable for swaps.
  • Merge sort is an out-of-place sort: it builds new lists as it merges, so it needs more memory than bubble sort.
  • On a large list, merge sort makes far fewer compares than bubble sort, so it usually takes much less time.
  • Fitness for purpose asks whether the algorithm does what is needed: use test data and logical reasoning to check it gives the right result, including for edge cases such as a missing target or an empty list.
AlgorithmBest caseWorst case
Linear searchTarget is the first item: 1 compareTarget is the last item or not there: every item is compared
Binary searchTarget is the first mid-point: 1 compareTarget found last or not there: about one compare per halving (4 for 10 items, 10 for 1000)
Bubble sortList already sorted: one pass, no swaps, n − 1 comparesList in reverse order: the most passes and swaps
Merge sortAlways splits and merges the whole listAlways splits and merges the whole list

In place v out of place

Exam tipFor a best or worst case, give the case and the reason: “the target is the last item, so every item has to be compared”. Examiners saw many answers that stopped after the case.
In-place sort
A sort that rearranges the items within the original list, needing very little extra memory (bubble sort).
Out-of-place sort
A sort that builds new lists as it works, so it needs extra memory (merge sort).
Fitness for purpose
Whether an algorithm does what it is meant to do, checked with logical reasoning and test data.
Edexcel 1CP2 · 1.2.7

Choosing an algorithm

  • Pick by the situation: how big the list is, whether it is sorted, how often it changes and how much memory there is.
  • A device with very little memory (an embedded system, for example) may use bubble sort even though it is slower.
  • A list that is searched thousands of times a day is worth keeping sorted, so binary search can be used.
Linear searchBinary search
Sorted list needed?NoYes
Compares on a large listUp to one per itemFar fewer: each compare halves what is left
Good forShort or unsorted lists, or lists that change oftenLong sorted lists searched many times
Bubble sortMerge sort
MemoryLess: in placeMore: out of place
Time on a large unsorted listSlow: many passes and comparesMuch quicker
Nearly sorted listQuick: may stop after one or two passesStill splits and merges everything
Exam tipDon't just write “faster” or “easier”. Say what makes it faster: “binary search makes fewer compares on a large sorted list, so it takes less time”.