GCSE Revision

Searching and sorting algorithms

The specification's two searches and three sorts, each played step by step, with its code in Exam Reference Language and Python. You don't need to remember the code, but you do need to recognise it, follow it, and apply each algorithm to a list. In these examples, items.length is the number of items in the array.

Bubble sort

Goes through the list comparing each pair of neighbours and swapping them if they're in the wrong order. Each pass moves the largest unsorted item to the end, and the passes repeat until the list is sorted. Simple, but slow on long lists.

bubble sort
514283

Start with 5, 1, 4, 2, 8, 3.

Step 1 of 15
procedure bubbleSort(items)
    n = items.length
    for i = 0 to n - 2
        for j = 0 to n - 2 - i
            if items[j] > items[j + 1] then
                temp = items[j]
                items[j] = items[j + 1]
                items[j + 1] = temp
            endif
        next j
    next i
endprocedure

Insertion sort

Takes each item in turn and inserts it into its place in the sorted part of the list, to its left, by moving bigger items one place right. The sorted part grows by one item each time.

insertion sort
514283

Start with 5, 1, 4, 2, 8, 3.

Step 1 of 13
procedure insertionSort(items)
    for i = 1 to items.length - 1
        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
endprocedure

Merge sort

Splits the list in half again and again until each part has one item, then merges the parts back together in order, taking the smaller front item each time, until one sorted list is left. It's usually the fastest of the three on long lists, but uses extra memory.

merge sort
514283

Start with 5, 1, 4, 2, 8, 3.

Step 1 of 16
procedure mergeSort(items, low, high)
    if low < high then
        mid = (low + high) DIV 2
        mergeSort(items, low, mid)
        mergeSort(items, mid + 1, high)
        merge(items, low, mid, high)
    endif
endprocedure

procedure merge(items, low, mid, high)
    array temp[high - low + 1]
    i = low
    j = mid + 1
    k = 0
    while i <= mid AND j <= high
        if items[i] <= items[j] then
            temp[k] = items[i]
            i = i + 1
        else
            temp[k] = items[j]
            j = j + 1
        endif
        k = k + 1
    endwhile
    while i <= mid
        temp[k] = items[i]
        i = i + 1
        k = k + 1
    endwhile
    while j <= high
        temp[k] = items[j]
        j = j + 1
        k = k + 1
    endwhile
    for k = 0 to high - low
        items[low + k] = temp[k]
    next k
endprocedure

More in the notes: Searching algorithms and Sorting algorithms.