Skip to content

2.1.3 Searching and sorting algorithms

GCSE · Paper 2 · Computational thinking, algorithms and programming · Section 2.1 · 20 flashcards · 12 practice questions

Questions

2.1.3 Searching and sorting algorithms

Computers search and sort data all the time: finding a contact in a phone, putting scores in order, looking up a product code. This topic covers two ways to search and three ways to sort. You need to know the main steps of each one, be able to apply it to a small set of data, and recognise it from code. You do not need to remember the code.

Searching

Definition
A searching algorithm finds out whether an item is in a list, and where it is.
Definition
A linear search checks each item in the list in turn, starting at the first, until it finds the item it wants or reaches the end of the list.

The steps are:

  • 1.
    Look at the first item.
  • 2.
    If it is the item you want, stop. You have found it.
  • 3.
    If not, move to the next item.
  • 4.
    If you reach the end of the list without a match, the item is not in the list.
Linear search works on any list. The data does not need to be in order.

Worked example

The list is 7, 3, 9, 4, 8 (index 0 to 4). The target is 4.

StepIndexItemIs it 4?
107No
213No
329No
434Yes, found at index 3

It took 4 comparisons. If the target had been 5, every item would be checked (5 comparisons) and the answer would be that 5 is not in the list.

pseudocode
function linearSearch(items, size, target)
    i = 0
    while i < size
        if items[i] == target then
            return i
        endif
        i = i + 1
    endwhile
    return -1
endfunction

You can recognise a linear search because one loop goes through the items from the start, and each item is compared with the target. The function returns -1 when the item is not found.

Definition
A binary search looks at the middle item of a sorted list. If it is not the target, it throws away the half that cannot hold the target and repeats on the other half.
Warning
Binary search only works on a list that is already sorted. If the data is not in order, you cannot tell which half to throw away.

The steps are:

  • 1.
    Set low to the first index and high to the last index.
  • 2.
    Find the middle index: mid = (low + high) DIV 2.
  • 3.
    If the item at mid is the target, stop. You have found it.
  • 4.
    If the item at mid is smaller than the target, the target must be to the right, so set low to mid + 1.
  • 5.
    If the item at mid is bigger than the target, the target must be to the left, so set high to mid - 1.
  • 6.
    Repeat from step 2. If low becomes bigger than high, there is nothing left to look at and the target is not in the list.
DIV gives the whole number part of a division. When there are two middle items (an even number of items), DIV takes the lower one. For example, with low = 0 and high = 5, (0 + 5) DIV 2 is 2, so index 2 is used, not index 3.

Worked example: item found

The sorted list is 3, 8, 12, 15, 21, 27, 30 (index 0 to 6). The target is 27.

lowhighmidItem at midWhat happens
0631515 is smaller than 27, so low = 4
46527Found at index 5

It took 2 comparisons. A linear search would have needed 6.

Worked example: an even number of items, item not found

The sorted list is 2, 5, 9, 14, 20, 26 (index 0 to 5). The target is 10.

lowhighmidItem at midWhat happens
05299 is smaller than 10, so low = 3
3542020 is bigger than 10, so high = 3
3331414 is bigger than 10, so high = 2
32low is bigger than high, so 10 is not in the list
pseudocode
function binarySearch(items, size, target)
    low = 0
    high = size - 1
    while low <= high
        mid = (low + high) DIV 2
        if items[mid] == target then
            return mid
        elseif items[mid] < target then
            low = mid + 1
        else
            high = mid - 1
        endif
    endwhile
    return -1
endfunction

You can recognise a binary search because it has low, high and mid variables, the middle is worked out inside the loop, and low or high is moved each time.

Pros & Cons
Binary searchLinear search
Needs the list to be sortedWorks on a sorted or unsorted list
Needs far fewer comparisons on a large listNeeds to check many items on a large list
Harder to writeSimple to write

Sorting

Definition
A sorting algorithm puts the items in a list into order, such as smallest to largest.

All the examples sort from smallest to largest.

Bubble sort

Definition
A bubble sort goes through the list comparing each pair of neighbouring items and swapping them if they are in the wrong order. It repeats this pass until a whole pass is made with no swaps.

After each pass the biggest item that is not yet in place has moved ("bubbled") to its place at the end. So each pass can be a little shorter than the one before.

Worked example

Sort 5, 2, 8, 1, 4.

PassComparisons and swapsList at the end of the pass
15 and 2 swap. 5 and 8 stay. 8 and 1 swap. 8 and 4 swap2, 5, 1, 4, 8
22 and 5 stay. 5 and 1 swap. 5 and 4 swap2, 1, 4, 5, 8
32 and 1 swap. 2 and 4 stay1, 2, 4, 5, 8
41 and 2 stay. No swaps, so the list is sorted1, 2, 4, 5, 8
pseudocode
array items = [5, 2, 8, 1, 4]
swapped = true
last = 4
while swapped == true
    swapped = false
    for i = 0 to last - 1
        if items[i] > items[i + 1] then
            temp = items[i]
            items[i] = items[i + 1]
            items[i + 1] = temp
            swapped = true
        endif
    next i
    last = last - 1
endwhile

You can recognise a bubble sort because of the swap (three lines using a temporary variable) inside a loop that compares items[i] with items[i + 1], and because the loop repeats until no swaps are made.

Key Point
Bubble sort is simple to write and easy to follow. It is slow on a long list because it makes many passes and many comparisons.

Insertion sort

Definition
An insertion sort builds a sorted list one item at a time. It takes the next item and inserts it in the correct place among the items already sorted.

The first item on its own counts as sorted. Then for each item after it, move along the sorted part from the right, shifting bigger items one place to the right, and put the item in the gap.

Worked example

Sort 6, 3, 8, 2, 5.

Item insertedWhat happensList after
Start6 is sorted on its own6, 3, 8, 2, 5
3Smaller than 6, so 6 shifts right and 3 goes first3, 6, 8, 2, 5
8Bigger than 6, so it stays where it is3, 6, 8, 2, 5
2Smaller than 8, 6 and 3, so all shift right and 2 goes first2, 3, 6, 8, 5
5Smaller than 8 and 6 but bigger than 3, so 5 goes between 3 and 62, 3, 5, 6, 8
pseudocode
array items = [6, 3, 8, 2, 5]
for i = 1 to 4
    current = items[i]
    j = i - 1
    while j >= 0 AND items[j] > current
        items[j + 1] = items[j]
        j = j - 1
    endwhile
    items[j + 1] = current
next i

You can recognise an insertion sort because the item being placed is stored in a variable (current), a loop shifts bigger items along, and the item is then put into the gap.

Merge sort

Definition
A merge sort splits the list in half again and again until every sublist has one item, then merges the sublists back together in order.

A list with one item is already sorted. Merging means taking two sorted lists and making one sorted list. To merge, compare the first item of each list, write down the smaller one, and repeat until one list is empty. Then add the rest of the other list.

The steps are:

  • 1.
    Divide the list into two halves.
  • 2.
    Keep dividing until every sublist has a single item.
  • 3.
    Merge pairs of sublists into sorted sublists.
  • 4.
    Keep merging until there is one sorted list.

Worked example

Sort 6, 3, 8, 2, 5, 1, 7, 4.

StageLists
Start6, 3, 8, 2, 5, 1, 7, 4
Divide6, 3, 8, 2 and 5, 1, 7, 4
Divide6, 3 and 8, 2 and 5, 1 and 7, 4
Divide6 and 3 and 8 and 2 and 5 and 1 and 7 and 4
Merge3, 6 and 2, 8 and 1, 5 and 4, 7
Merge2, 3, 6, 8 and 1, 4, 5, 7
Merge1, 2, 3, 4, 5, 6, 7, 8

The last merge of 2, 3, 6, 8 with 1, 4, 5, 7 goes like this. Compare 2 and 1: write 1. Compare 2 and 4: write 2. Compare 3 and 4: write 3. Compare 6 and 4: write 4. Compare 6 and 5: write 5. Compare 6 and 7: write 6. Compare 8 and 7: write 7. Only 8 is left, so write 8.

You can recognise a merge sort from a description of dividing into halves and then merging. You do not need to write its code.

Comparing the algorithms

AlgorithmNeeds sorted data?Main ideaGood pointsWeak points
Linear searchNoCheck each item in turnSimple, works on any listSlow on a large list
Binary searchYesKeep halving the part of the list that is leftVery few comparisons on a large listList must be sorted first
Bubble sort-Swap neighbouring items that are in the wrong orderSimple to writeSlow on a long list
Insertion sort-Insert each item into a sorted partSimple, fast if the list is nearly sortedSlow on a long, mixed-up list
Merge sort-Divide to single items and merge in orderMuch faster on a long listHarder to write and needs extra memory for the sublists
Exam Tip
When you compare algorithms, use words like "fewer comparisons", "a large list" and "already sorted". A bare "it is faster" earns nothing. Say why it is faster.
Remember
Binary search needs a sorted list. The middle is (low + high) DIV 2, and with two middle items the lower one is taken. Bubble sort swaps neighbours, insertion sort inserts into a sorted part, merge sort divides then merges.

Exam technique

* State or name: give the name of the algorithm or the prerequisite, such as "the data must be sorted".
* Apply or show: write out the list after each pass, insertion or merge, or the low, high and mid values for each step of a binary search. Do not skip steps.
* Identify from code: look for the clues in the code, such as low, high and mid for binary search, a swap inside a loop for bubble sort, or a variable holding the item to insert for insertion sort.
* Describe: list the main steps in order.
* Compare or explain: write about both algorithms, give a reason and use the words "fewer comparisons", "sorted" and "large list".