KS4J277 2.1.3 38 min read 10 question quiz 19 exam marks

Searching and Sorting Algorithms

Linear and binary search, bubble, merge and insertion sort. How each one works step by step, and exactly when to choose which.

Linear search checks each item in turn from the start until it finds what it is looking for or reaches the end.

OCR reference language
function linearSearch(list, target)
    for i = 0 to list.length - 1
        if list[i] == target then
            return i
        endif
    next i
    return -1
endfunction

Characteristics

  • Works on any list, sorted or unsorted
  • Simple to write and understand
  • Slow on large lists: in the worst case it checks every item
  • On a list of n items, the worst case is n comparisons

When to use it

  • The list is unsorted, and sorting it first would cost more than the search saves
  • The list is small
  • You only need to search once
Linear search and binary search, looking for 38Two ways of finding the number 38 in a sorted list of fifteen numbers. In a linear search the program looks at the items one at a time from the left, so it has to look at the first nine and reject each one before it finds 38 on the tenth look. In a binary search the program checks the middle item, which is 30. 38 is bigger, so the whole left half is thrown away. It then checks the middle of what is left, which is 47. 38 is smaller, so the right half is thrown away, leaving three items. The middle of those is 38, found on the third look. Binary search takes 3 looks where linear search took 10, and the gap grows as the list grows, but binary search only works if the list is sorted.Linear search: look at every item in turn381114172126303338424751566012345678910not it, not it, not it ...found it on the 10th look1Binary search: halve the sorted list every time3811141721263033384247515660check the middle: 30. 38 is bigger, so drop the left half3811141721263033384247515660check the middle: 47. 38 is smaller, so drop the right half3811141721263033384247515660check the middle: 38. Found it, on the 3rd look2linear: 10 looksbinary: 3 looksbinary search needs a sorted list3
  1. Linear search looks at every item in turn from the start, so it can be slow.
  2. Binary search checks the middle and throws half the list away each time.
  3. 3 looks against 10. The longer the list, the bigger the gap, but binary search needs the list sorted.
Linear works on any list. Binary is far faster, but only on a sorted one.

Binary search repeatedly halves the search area. It requires the list to be sorted.

  1. Find the middle item.
  2. If it is the target, stop.
  3. If the target is smaller, discard the whole upper half and repeat on the lower half.
  4. If the target is larger, discard the lower half and repeat on the upper half.
  5. Repeat until found, or until there are no items left.
OCR reference language
function binarySearch(list, target)
    low = 0
    high = list.length - 1
    while low <= high
        mid = (low + high) DIV 2
        if list[mid] == target then
            return mid
        elseif list[mid] < target then
            low = mid + 1
        else
            high = mid - 1
        endif
    endwhile
    return -1
endfunction

Worked example

Find 23 in [4, 8, 15, 16, 23, 42, 50]

StepRangeMiddleCompareAction
14 to 501623 > 16Discard lower half
223 to 504223 < 42Discard upper half
32323FoundStop

Three comparisons instead of five.

Characteristics

  • Much faster on large lists, because each comparison removes half the remaining items
  • Requires a sorted list, which is a real cost if the data is not already sorted
  • More complex to implement than linear search
The comparison examiners want

Binary search is far more efficient than linear search on large sorted lists because each comparison eliminates half of the remaining items, whereas linear search eliminates only one. However, binary search can only be used if the list is already sorted.

Binary search halving the list three timesBinary search looking for 12 in the sorted list 2, 5, 8, 12, 16, 23, 38, 56, 72, 91, 100. Step one sets low to the first item and high to the last, giving a midpoint of 23. The target 12 is smaller than 23, so the whole right half including 23 is discarded. Step two searches 2, 5, 8, 12, 16 with a midpoint of 8. The target 12 is bigger than 8, so 8 and everything to its left is discarded. Step three searches 12 and 16 with a midpoint of 12, which is the target, so the search succeeds after three comparisons rather than the four a linear search would need.Binary search for 12 in a sorted list of 11 items2low58121623mid38567291100highmidpoint is 23. 12 is smaller, so throw away 23 and everything right2low58mid1216high2338567291100midpoint is 8. 12 is bigger, so throw away 8 and everything left25812lowmid16high2338567291100midpoint is 12. Found it, after only three comparisons
Binary search only works on a sorted list. Doubling the list length adds just one extra comparison, which is why it scales so well.

Bubble sort

Bubble sort repeatedly steps through the list, comparing each pair of adjacent items and swapping them if they are in the wrong order. After each full pass, the largest remaining value has moved to its correct position at the end.

OCR reference language
procedure bubbleSort(list)
    swapped = true
    while swapped == true
        swapped = false
        for i = 0 to list.length - 2
            if list[i] > list[i+1] then
                temp = list[i]
                list[i] = list[i+1]
                list[i+1] = temp
                swapped = true
            endif
        next i
    endwhile
endprocedure

Worked pass

Starting list: [5, 3, 8, 1]

Pass 1

  • Compare 5 and 3, swap: [3, 5, 8, 1]
  • Compare 5 and 8, no swap: [3, 5, 8, 1]
  • Compare 8 and 1, swap: [3, 5, 1, 8]

8 is now in its final position.

Pass 2: [3, 1, 5, 8] Pass 3: [1, 3, 5, 8] Pass 4: no swaps made, so the list is sorted and the algorithm stops.

Characteristics

  • Very simple to understand and write
  • Uses very little extra memory, because it sorts in place
  • Very slow on large lists, since it may need to pass through the list many times
  • Good for small lists or nearly sorted lists
Bubble sort worked through pass by passBubble sort applied to the list 5, 1, 4, 2, 8. In pass one the algorithm compares each neighbouring pair from the left. It compares 5 and 1, 5 is bigger so they swap, giving 1, 5, 4, 2, 8. It compares 5 and 4 and swaps, giving 1, 4, 5, 2, 8. It compares 5 and 2 and swaps, giving 1, 4, 2, 5, 8. It compares 5 and 8, 5 is smaller so nothing moves, and the largest value 8 has bubbled to the end and is now in its final place. Pass two makes one swap, of 4 and 2, giving 1, 2, 4, 5, 8, and 5 is now also in place. Pass three makes no swaps at all, which tells the algorithm the list is sorted and it can stop.Bubble sort on 5, 1, 4, 2, 8start51428pass 1514285 is bigger than 1, so swap154285 is bigger than 4, so swap145285 is bigger than 2, so swap142585 is smaller than 8, leave itpass 212458one swap this pass, 5 is now in placepass 312458no swaps at all, so the list is sorted
After pass one the largest value is definitely at the end. After pass two the two largest are. A pass with no swaps means the list is sorted.
Bubble sort on 5, 2, 4, 1, 3Bubble sort drawn with numbered cards. On the left is the first pass, step by step. The two cards being compared are lit up. 5 is bigger than 2, so they swap. 5 is bigger than 4, so they swap again. 5 is bigger than 1 and then 3, and swaps each time, so the 5 has bubbled all the way to the end, where it is in its final place and is shown in green. On the right is the list after every pass: after pass 1 the 5 is in place, after pass 2 the 4 and 5, and after pass 3 the whole list is in order. Pass 4 makes no swaps at all, which is how the algorithm knows it can stop.One pass, step by step524135 > 2: swap254135 > 4: swap245135 > 1: swap241535 > 3: swap241355 is in place123After every passstart52413pass 124135pass 221345pass 312345pass 412345pass 4 made no swaps,so the list is sortedstop when a pass makes no swaps4
  1. Compare two neighbours, and if they are the wrong way round, swap them.
  2. Work along the list. A big value is carried all the way to the end.
  3. After a pass the last item is in its final place, so the next pass can be shorter.
  4. Repeat until a whole pass makes no swaps.
Each pass puts one more item in place. A pass with no swaps means the list is sorted.

Merge sort

Merge sort uses divide and conquer. It splits the list in half repeatedly until every list contains one item, then merges pairs of lists back together in order.

The two phases

Divide: split the list in half, then split each half in half, and continue until each sub list has exactly one item. A list of one item is by definition sorted.

Merge: repeatedly merge pairs of sub lists. To merge two sorted lists, compare the first item of each, take the smaller, and repeat until both are empty.

Worked example

Sort [6, 2, 8, 4, 1]

Divide: [6, 2, 8, 4, 1] [6, 2] [8, 4, 1] [6] [2] [8] [4, 1] [4] [1]

Merge: [2, 6] [1, 4] then [1, 4, 8] [1, 2, 4, 6, 8]

Characteristics

  • Much faster than bubble sort on large lists, and its performance is consistent
  • Efficient regardless of how disordered the starting list is
  • Uses more memory, because the sub lists must be stored separately
  • More complex to implement
The memory point is worth a mark

Merge sort is faster but not free. It requires additional memory to hold the sub lists, whereas bubble and insertion sort work in place.

Merge sort: the divide phase and the merge phaseMerge sort on the list 38, 27, 43, 3, 9, 82, 10, 1. The divide phase splits the list in half repeatedly: first into 38, 27, 43, 3 and 9, 82, 10, 1; then into 38, 27 and 43, 3 and 9, 82 and 10, 1; then into eight single item lists. A list of one item is already sorted. The merge phase then combines pairs, each time comparing the front items of the two lists and taking the smaller. The pairs become 27, 38 and 3, 43 and 9, 82 and 1, 10. Those merge into 3, 27, 38, 43 and 1, 9, 10, 82. Those merge into the final sorted list 1, 3, 9, 10, 27, 38, 43, 82.DIVIDE: split in half until every list holds one item3827433982101382743398210138274339821013827433982101273834398211032738431910821391027384382MERGE: rebuild in pairs, always taking the smaller front item
Merge sort always takes about n log n comparisons, whatever order the list starts in, but it needs extra memory to hold the part lists.
Merge sort on eight numbers: divide, then mergeMerge sort drawn as a diamond of numbered cards, read from the top down and then back up. The list of eight numbers, 6 3 8 1 7 2 5 4, is divided in half again and again: first into two groups of four, then four groups of two, then eight single cards. A single card is already sorted. Then the groups are merged back together, working upwards. Each merge compares the front card of the two groups and takes the smaller one every time, so the pairs become 3 6, 1 8, 2 7 and 4 5, then the groups of four become 1 3 6 8 and 2 4 5 7, and finally the whole list is merged into 1 2 3 4 5 6 7 8.63817254638172546381725463817254361827451368245712345678dividemerge1 item is sortedto merge:compare thefront of eachgroup, take thesmaller one123
  1. Divide the list in half, again and again.
  2. Stop when every group is a single item. One item is already sorted.
  3. Merge groups back together, taking the smaller front item each time, until one sorted list is left.
Merge sort divides until the pieces are trivial, then does all its real work while merging.

Insertion sort

Insertion sort builds a sorted section at the start of the list. It takes the next unsorted item and inserts it into the correct position within the sorted section, shifting larger items along to make room.

This is exactly how most people sort a hand of playing cards.

OCR reference language
procedure insertionSort(list)
    for i = 1 to list.length - 1
        current = list[i]
        j = i - 1
        while j >= 0 AND list[j] > current
            list[j+1] = list[j]
            j = j - 1
        endwhile
        list[j+1] = current
    next i
endprocedure

Worked example

[5, 2, 9, 1]

  • Take 2, insert before 5: [2, 5, 9, 1]
  • Take 9, already in place: [2, 5, 9, 1]
  • Take 1, insert at the front: [1, 2, 5, 9]

Characteristics

  • Simple, and sorts in place so uses very little extra memory
  • Very efficient on nearly sorted lists, because most items need almost no movement
  • Slow on large disordered lists
  • Can sort data as it arrives, without needing the whole list first
Insertion sort on 4, 3, 5, 1, 2Insertion sort drawn as sorting playing cards in your hand. The sorted cards, in green, sit on the left and the unsorted cards, in grey, on the right, with the card currently being placed lifted up in yellow. Start with just the 4 as the sorted part. Take 3: it is smaller than 4, so the 4 shifts right and the 3 goes in front. Take 5: it is bigger than 4, so it stays where it is. Take 1: it is smaller than 3, 4 and 5, so all three shift right and the 1 goes at the front. Take 2: the 3, 4 and 5 shift right and the 2 drops in after the 1. No cards are left, so the list is sorted.like sorting playing cards in your hand43512take 3: it is smaller than 4, so 4 shifts right34512take 5: bigger than 4, so it stays where it is34512take 1: shift 3, 4 and 5 right, then drop it in front13452take 2: shift 3, 4 and 5 right, drop it after 112345no cards left: the list is sorted1234
  1. The sorted part grows from the left, one card at a time.
  2. Take the next card and slide it back past every larger card.
  3. Larger cards shift one place right to make room.
  4. When no cards are left, the whole list is sorted.
Insertion sort is quick on lists that are nearly sorted already, and simple to write.

Choosing an algorithm

AlgorithmSpeed on large listsMemory usedNeeds sorted dataBest for
Linear searchSlowVery littleNoSmall or unsorted lists
Binary searchFastVery littleYesLarge sorted lists
Bubble sortVery slowVery littlen/aSmall lists, teaching
Insertion sortSlowVery littlen/aSmall or nearly sorted lists
Merge sortFastMoren/aLarge lists

How exam questions phrase it

  • "A list of 2 million sorted records" points to binary search.
  • "An unsorted list that is searched once" points to linear search.
  • "Sorting a very large dataset" points to merge sort, and mention the memory cost.
  • "A device with very limited memory" points to bubble or insertion sort.
  • "Data that is almost in order already" points to insertion sort.
Always justify with the property of the data

The mark is not for naming the algorithm. It is for linking the choice to whether the data is sorted, how large it is, how disordered it is, and how much memory is available.

Sorting algorithm visualiser

Run bubble, insertion, merge and quick sort side by side and count the comparisons. This tool needs JavaScript, so turn it on to use it. Everything you need to answer the exam question is explained in the text above.

Key terms you must be able to define

Linear search
Checking each item in a list in turn until the target is found or the end is reached.
Binary search
Repeatedly halving a sorted list by comparing the target with the middle item.
Bubble sort
Repeatedly comparing adjacent items and swapping them if they are in the wrong order.
Merge sort
Splitting a list into single items then repeatedly merging sorted sub lists back together.
Insertion sort
Building a sorted section by inserting each next item into its correct position within it.
Divide and conquer
Solving a problem by breaking it into smaller instances of the same problem.
In place
An algorithm that sorts using only a small constant amount of extra memory.
Pass
One complete run through a list during a sorting algorithm.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineLinear search
AnswerChecking each item in a list in turn until the target is found or the end is reached.
DefineBinary search
AnswerRepeatedly halving a sorted list by comparing the target with the middle item.
DefineBubble sort
AnswerRepeatedly comparing adjacent items and swapping them if they are in the wrong order.
DefineMerge sort
AnswerSplitting a list into single items then repeatedly merging sorted sub lists back together.
DefineInsertion sort
AnswerBuilding a sorted section by inserting each next item into its correct position within it.
DefineDivide and conquer
AnswerSolving a problem by breaking it into smaller instances of the same problem.
DefineIn place
AnswerAn algorithm that sorts using only a small constant amount of extra memory.
DefinePass
AnswerOne complete run through a list during a sorting algorithm.

Reach the top grade on this topic

The examinable skills here are tracing and justifying.

Tracing. You will be asked to show the state of a list after one or two passes of a sort. Write the list out after every single comparison during a bubble sort pass, and after every insertion during an insertion sort. Do not do it in your head.

Justifying. When choosing an algorithm, name the property of the data that drives the choice.

Weak: "Binary search is better because it is faster." Strong: "Binary search is more suitable because the list of 50,000 records is already sorted, and each comparison eliminates half of the remaining records, so at most about 16 comparisons are needed instead of up to 50,000."

Know the trade offs, not just the speeds. Merge sort is faster but needs more memory. Bubble sort is slow but needs almost none. Binary search is faster but demands sorted data.

  • Trace one full pass of bubble sort on a five item list, writing the list after every swap
  • Show every step of a binary search including which half is discarded and why
  • Explain why merge sort uses more memory than bubble sort
  • Choose and justify an algorithm for any scenario, naming the property of the data

Mistakes that cost marks here

Avoid these
  • Using binary search on an unsorted list. It gives wrong answers, and saying so is worth a mark.
  • Saying merge sort is 'always better'. It uses more memory, which matters on constrained devices.
  • Confusing bubble sort with insertion sort. Bubble compares adjacent pairs, insertion places each item into a sorted section.
  • Only writing the final sorted list when asked to show one pass. Show the intermediate states.
  • Saying an algorithm is faster without saying why, in terms of the number of comparisons.
Fun fact

Binary search finds an item in a sorted list of one million entries in at most twenty comparisons. Linear search would need up to a million. That gap is why sorting data first is often worth the effort.

Knowledge check

0 of 10 answered
1Which search algorithm requires the list to be sorted?
2A list of 1000 sorted items is searched. What is the approximate maximum number of comparisons for a binary search?
3In one full pass of bubble sort, what is guaranteed to happen?
4Which sorting algorithm uses divide and conquer?
5What is the main disadvantage of merge sort compared with bubble sort?
6After the first pass of bubble sort on [7, 3, 9, 2], the list is:
7Which algorithm is most efficient on a list that is already nearly sorted?
8Binary search on the sorted list [2, 5, 9, 14, 20, 31, 44] looking for 5 first compares against:
9Why is linear search sometimes preferred over binary search?
10Insertion sort works by:
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

19 marks
1Describe how a binary search finds an item in a sorted list.4 marks
Describe

Mark scheme0 / 4
  • LThe middle item of the list is examined
  • LIf it matches the target the search stops
  • LIf the target is smaller the upper half is discarded, if larger the lower half is discarded
  • LThe process repeats on the remaining half until the item is found or no items remain
Model answer

Binary search begins by examining the item in the middle of the sorted list. If that item is the one being searched for, the search stops and the position is returned. If the target is smaller than the middle item then it cannot be in the upper half, so the entire upper half including the middle item is discarded. If the target is larger then the lower half is discarded instead. The process then repeats on whichever half remains, examining its middle item and discarding half again, and continues until either the item is found or the remaining range is empty, in which case the item is not in the list.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Show the state of the list [8, 4, 6, 2] after each pass of a bubble sort.4 marks
Show

Mark scheme0 / 4
  • LAfter pass 1 the list is [4, 6, 2, 8]
  • LAfter pass 2 the list is [4, 2, 6, 8]
  • LAfter pass 3 the list is [2, 4, 6, 8]
  • LShows that a final pass with no swaps confirms the list is sorted
Model answer

Pass 1: comparing 8 and 4 gives a swap to [4, 8, 6, 2]; comparing 8 and 6 gives a swap to [4, 6, 8, 2]; comparing 8 and 2 gives a swap to [4, 6, 2, 8]. Pass 2: comparing 4 and 6 gives no swap; comparing 6 and 2 gives a swap to [4, 2, 6, 8]; comparing 6 and 8 gives no swap. Pass 3: comparing 4 and 2 gives a swap to [2, 4, 6, 8]; the remaining comparisons give no swaps. A fourth pass makes no swaps at all, which tells the algorithm that the list is fully sorted and it stops.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Compare bubble sort and merge sort in terms of speed and memory use.4 marks
Compare

Mark scheme0 / 4
  • LMerge sort is much faster on large lists
  • LBubble sort may pass through the list many times, making it very slow on large data
  • LBubble sort sorts in place, using very little extra memory
  • LMerge sort needs additional memory to store the sub lists during merging
Model answer

In terms of speed, merge sort is substantially faster than bubble sort on large lists. Bubble sort compares every adjacent pair on each pass and may need to pass through the whole list many times, so the number of comparisons grows very steeply as the list gets longer. Merge sort repeatedly halves the problem and then merges sorted sub lists, which keeps the number of operations far lower and, importantly, gives consistent performance regardless of how disordered the original list is. The trade off is memory. Bubble sort operates in place, swapping items within the original list and needing only a single temporary variable, so its memory requirement is tiny. Merge sort has to create and hold the sub lists it produces while dividing and merging, so it requires additional memory roughly proportional to the size of the list, which can matter on devices where memory is limited.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A company stores 5 million customer records in a sorted list. Explain which search algorithm they should use and why.4 marks
Explain

Mark scheme0 / 4
  • LRecommends binary search
  • LThe list is already sorted, which binary search requires
  • LEach comparison eliminates half the remaining records
  • LOnly around 23 comparisons are needed instead of up to 5 million
Model answer

The company should use a binary search. The essential precondition is already met, because the records are stored in sorted order, and binary search cannot be used on unsorted data. Each comparison in a binary search eliminates half of the records still under consideration, so the number of items to check falls from 5 million to 2.5 million to 1.25 million and so on. This means the target is found in roughly 23 comparisons at most, since 2 to the power 23 is over 8 million. A linear search on the same data would examine records one at a time and could require up to 5 million comparisons, so the binary search is several hundred thousand times faster in the worst case, which matters enormously if searches are performed frequently.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain why an insertion sort may be a better choice than a merge sort for a small embedded device with very limited memory.3 marks
Explain

Mark scheme0 / 3
  • LInsertion sort works in place and requires very little extra memory
  • LMerge sort requires additional memory to hold sub lists
  • LOn a device with limited memory, saving memory outweighs the speed advantage, especially for small lists
Model answer

An insertion sort operates entirely within the original list, moving items along to make space and using only a single temporary variable, so its additional memory requirement is effectively constant no matter how large the list is. A merge sort, by contrast, must create and store the sub lists it produces while dividing and merging, which requires extra memory roughly proportional to the size of the data. On an embedded device with very limited memory that extra allocation may simply not be available, and attempting it could cause the program to fail. Since embedded systems also tend to handle relatively small quantities of data, where the speed advantage of merge sort is small in absolute terms, the memory saving of insertion sort is the more important consideration.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 19