KS41CP2 1.2 36 min read 10 question quiz 19 exam marks

Searching and Sorting Algorithms

Linear search, binary search, bubble sort and merge sort: how each one moves through the data, how to trace it, and how to justify choosing one over another.

Linear search

Linear search starts at the first item and checks each one in turn until it finds the target or runs out of list.

PSEUDOCODE
FUNCTION linearSearch(items, target)
    FOR position FROM 0 TO LENGTH(items) - 1 DO
        IF items[position] = target THEN
            RETURN position
        END IF
    END FOR
    RETURN -1
END FUNCTION

Its strength is that it makes no demands on the data. The list can be in any order, and no preparation is needed. Its weakness is speed: on a list of n items the worst case is n comparisons, so searching a million records could mean a million checks.

Binary search

Binary search only works on a sorted list. It looks at the middle item, and because the list is sorted, one comparison tells it which half the target must be in. The other half is discarded entirely.

  1. Find the middle item of the search area.
  2. If it is the target, stop.
  3. If the target is smaller, discard the middle item and everything above it.
  4. If the target is larger, discard the middle item and everything below it.
  5. Repeat on what is left, until the target is found or nothing remains.
PSEUDOCODE
FUNCTION binarySearch(items, target)
    SET low TO 0
    SET high TO LENGTH(items) - 1
    WHILE low <= high DO
        SET mid TO (low + high) DIV 2
        IF items[mid] = target THEN
            RETURN mid
        ELSE IF items[mid] < target THEN
            SET low TO mid + 1
        ELSE
            SET high TO mid - 1
        END IF
    END WHILE
    RETURN -1
END FUNCTION

Worked example

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

StepSearch areaMiddleComparisonAction
14 to 501623 is greater than 16Discard 4, 8, 15, 16
223 to 504223 is less than 42Discard 42, 50
323 only23FoundStop

Three comparisons. Linear search would have taken five.

Why halving wins

Each linear comparison rules out one item. Each binary comparison rules out half of everything that is left. On large lists that difference is the whole ball game, but it is bought with the requirement that the list is sorted first.

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.
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.

Bubble sort

Bubble sort repeatedly walks through the list comparing each pair of neighbours and swapping them if they are the wrong way round. After the first full pass the largest value has been carried all the way to the end, which is where the name comes from.

PSEUDOCODE
PROCEDURE bubbleSort(items)
    SET swapped TO TRUE
    WHILE swapped = TRUE DO
        SET swapped TO FALSE
        FOR i FROM 0 TO LENGTH(items) - 2 DO
            IF items[i] > items[i + 1] THEN
                SET temp TO items[i]
                SET items[i] TO items[i + 1]
                SET items[i + 1] TO temp
                SET swapped TO TRUE
            END IF
        END FOR
    END WHILE
END PROCEDURE

Tracing one pass

Start with [7, 3, 9, 2].

  • Compare 7 and 3. Wrong order, swap: [3, 7, 9, 2]
  • Compare 7 and 9. Correct order, leave: [3, 7, 9, 2]
  • Compare 9 and 2. Wrong order, swap: [3, 7, 2, 9]

End of pass one. 9 is now in its final position. Pass two produces [3, 2, 7, 9], pass three produces [2, 3, 7, 9], and pass four makes no swaps at all, which is how the algorithm knows it has finished.

Why the swapped flag matters

Without the flag the algorithm has no way of knowing the list is already sorted, and would carry on making pointless passes. With it, a list that is already in order is confirmed sorted in a single pass. This is why bubble sort is respectable on nearly sorted data and dreadful on everything else.

A pass is not a comparison

Questions ask both "how many passes" and "how many comparisons". One pass over a list of n items makes n minus 1 comparisons. Read which one is being asked for.

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 over and over until every piece holds a single item, then builds the answer back up by merging pairs of sorted pieces.

The insight it rests on is that a list of one item is already sorted, and that merging two sorted lists is easy: compare the first item of each, take the smaller, repeat.

Divide

[6, 2, 8, 4, 1] splits into [6, 2] and [8, 4, 1], which split into [6], [2], [8] and [4, 1], and finally [4, 1] splits into [4] and [1].

Merge

  • Merge [6] and [2] to get [2, 6]
  • Merge [4] and [1] to get [1, 4]
  • Merge [8] and [1, 4] to get [1, 4, 8]
  • Merge [2, 6] and [1, 4, 8] to get [1, 2, 4, 6, 8]

Why it is fast, and what it costs

Splitting a list of n items in half repeatedly takes about log2n rounds, and each round of merging touches every item once. On a list of 1000 items that is roughly 10 rounds of 1000 operations, about 10000 steps, against bubble sort's worst case of nearly 500000. The comparison is not close.

The cost is memory. Merge sort has to hold the sub lists separately while it merges them, so it needs additional space roughly the size of the original list. Bubble sort works in place and needs room for a single temporary variable. On a device with very little RAM that trade off can decide the choice.

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.

Choosing and comparing

Edexcel asks you to compare algorithms and justify a choice. The marks are in the reasoning, so learn the trade offs rather than a ranking.

Linear searchBinary search
List must be sortedNoYes
Worst case on n itemsn comparisonsAbout log2n comparisons
Best case1 comparison1 comparison
Good forSmall or unsorted lists, one off searchesLarge lists that are already sorted or searched repeatedly
Bubble sortMerge sort
MethodRepeated swapping of neighboursDivide the list, then merge sorted pieces
Speed on large listsVery slowMuch faster and consistent
Extra memoryAlmost none, sorts in placeSignificant, sub lists are held separately
Easiest to writeYesNo
Good forSmall or nearly sorted listsLarge lists where speed matters

Building the justification

The structure that scores is: name the algorithm, give the property of the data that makes it suitable, then give the consequence.

"For a list of 50000 sorted product codes searched thousands of times a day, binary search is the better choice. The list is already sorted, so the precondition costs nothing, and each comparison eliminates half of the remaining codes, so a search takes at most about 16 comparisons instead of up to 50000. Over thousands of searches that difference is enormous."

Never answer 'binary search is faster' and stop

That is one mark. The marks after it come from saying why it is faster, that it requires a sorted list, and what that requirement costs if the data is not already sorted.

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
A search that checks each item in a list in turn from the start until the target is found or the end is reached.
Binary search
A search that repeatedly examines the middle item of a sorted list and discards the half that cannot contain the target.
Bubble sort
A sort that repeatedly compares adjacent items and swaps them if they are in the wrong order until a pass makes no swaps.
Merge sort
A sort that repeatedly divides the list into halves until each holds one item, then merges the pieces back together in order.
Divide and conquer
A strategy that solves a problem by breaking it into smaller instances of the same problem and combining the results.
Pass
One complete run through the list by a sorting algorithm.
Comparison
One test of two values against each other, used as the standard measure of how much work a search or sort does.
Efficiency
A measure of the resources an algorithm uses, usually the number of comparisons or steps and the amount of memory required.
In place
A description of an algorithm that rearranges the data using almost no additional memory.

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
AnswerA search that checks each item in a list in turn from the start until the target is found or the end is reached.
DefineBinary search
AnswerA search that repeatedly examines the middle item of a sorted list and discards the half that cannot contain the target.
DefineBubble sort
AnswerA sort that repeatedly compares adjacent items and swaps them if they are in the wrong order until a pass makes no swaps.
DefineMerge sort
AnswerA sort that repeatedly divides the list into halves until each holds one item, then merges the pieces back together in order.
DefineDivide and conquer
AnswerA strategy that solves a problem by breaking it into smaller instances of the same problem and combining the results.
DefinePass
AnswerOne complete run through the list by a sorting algorithm.
DefineComparison
AnswerOne test of two values against each other, used as the standard measure of how much work a search or sort does.
DefineEfficiency
AnswerA measure of the resources an algorithm uses, usually the number of comparisons or steps and the amount of memory required.

Reach the top grade on this topic

Every question here rewards the same two moves: trace accurately and justify with a trade off.

Traces must show the state after each step. A merge sort question asking you to show the divide stage wants every level of splitting written out, not just the final answer. A bubble sort question asking for the list after two passes wants the list after pass one as well, because that is where the working marks live.

Every advantage has a matching cost. Binary search is faster but demands a sorted list. Merge sort is faster but demands more memory. Bubble sort is slow but simple and works in place. An answer that gives an advantage without acknowledging the cost is an average answer.

Quote numbers when you can. "Binary search would take at most 17 comparisons on 100000 records instead of up to 100000" is far stronger than "binary search is quicker", and it takes the same amount of time to write.

  • Be able to trace a binary search on a sorted list of nine items and state the number of comparisons
  • Be able to give the list after each pass of a bubble sort on a list of five values
  • Be able to draw the full divide and merge stages of a merge sort on six values
  • Be able to state the worst case number of comparisons for linear and binary search on n items
  • Be able to justify a choice of algorithm for a stated scenario in three sentences

Mistakes that cost marks here

Avoid these
  • Using binary search on an unsorted list. It does not simply run more slowly, it returns the wrong answer.
  • Confusing passes with comparisons. A single pass over n items makes n minus 1 comparisons.
  • Saying merge sort is better than bubble sort in every way. Merge sort needs considerably more memory because the sub lists must be stored.
  • Forgetting that bubble sort stops early when a pass makes no swaps, which is what makes it acceptable on nearly sorted data.
  • Writing that linear search is 'always slow'. On a small list, or when the target is near the front, it is perfectly efficient and needs no sorting first.
  • Splitting a merge sort list into groups of two and stopping there. The division continues until every sub list holds exactly one item.
Fun fact

Binary search halves the list every comparison, so ten comparisons cover 1024 items and twenty cover just over a million. That is why a phone can look a word up in a dictionary of half a million entries the instant you stop typing.

Knowledge check

0 of 10 answered
1What is the essential requirement before a binary search can be used?
2A sorted list contains 1000 items. Approximately how many comparisons does a binary search need in the worst case?
3After one complete pass of a bubble sort on [7, 3, 9, 2], the list is:
4How does merge sort know when to stop dividing the list?
5Which is the main disadvantage of merge sort compared with bubble sort?
6A programmer must search an unsorted list of 20 names once. Which is the sensible choice?
7What does the swapped flag in a bubble sort allow the algorithm to do?
8Binary search is applied to [2, 5, 9, 14, 20, 27, 31] looking for 5. What is the first item examined?
9Which statement about linear search is correct?
10In the worst case, how many comparisons does a linear search make on a list of n items?
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
1State two advantages of a binary search over a linear search on a large sorted list.2 marks
State

Mark scheme0 / 2
  • LFewer comparisons are needed so the search is faster
  • LEach comparison eliminates half of the remaining items
Model answer

A binary search needs far fewer comparisons than a linear search on a large list, so it finds the item much more quickly. This is because each comparison removes half of the remaining items from the search, whereas a linear search only removes one item at a time.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Describe how a bubble sort would sort the list [5, 1, 4, 2] into ascending order.4 marks
Describe

Mark scheme0 / 4
  • LAdjacent pairs of items are compared
  • LThey are swapped if they are in the wrong order
  • LThis is repeated in further passes through the list
  • LThe algorithm stops when a complete pass makes no swaps
Model answer

The algorithm compares the first two items, 5 and 1, finds them in the wrong order and swaps them to give 1, 5, 4, 2. It then compares 5 and 4, swaps them to give 1, 4, 5, 2, and compares 5 and 2, swapping them to give 1, 4, 2, 5, which completes the first pass and leaves the largest value at the end. A second pass compares 1 and 4 with no swap, then 4 and 2 with a swap, giving 1, 2, 4, 5. A third pass makes no swaps at all, and because nothing needed to move the algorithm knows the list is sorted and stops.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain how a merge sort sorts a list of numbers.4 marks
Explain

Mark scheme0 / 4
  • LThe list is repeatedly divided in half
  • LUntil each sub list contains only one item, which is sorted by definition
  • LPairs of sub lists are then merged back together
  • LDuring each merge the first item of each sub list is compared and the smaller is taken first
Model answer

A merge sort begins by dividing the list into two halves, then dividing each of those halves again, and continuing until every sub list contains exactly one item. A list of one item is already in order, which is why this is a sensible place to stop. The algorithm then merges the sub lists back together in pairs: to merge two sorted sub lists it compares the first item of each, takes whichever is smaller and places it into the new list, then repeats until both sub lists are empty. Each merge produces a longer sorted list, and the process continues until a single sorted list containing every original item remains.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A company stores 200000 customer records sorted by customer number. The records are searched several thousand times each day. Justify the use of a binary search rather than a linear search.4 marks
Justify

Mark scheme0 / 4
  • LThe records are already sorted, so the requirement of binary search is met at no extra cost
  • LEach comparison halves the number of records still to be searched
  • LAt most about 18 comparisons are needed instead of up to 200000
  • LBecause the search is repeated thousands of times a day the saving is large, reducing processing time and server load
Model answer

A binary search is the right choice here because the records are already held in order of customer number, so the one condition binary search imposes is already satisfied and costs nothing to meet. Each comparison in a binary search discards half of the records still under consideration, so a file of 200000 records is reduced to one in at most about eighteen comparisons, since two to the power eighteen is greater than 200000. A linear search would in the worst case examine all 200000 records to reach the same answer. Because the search runs several thousand times a day the difference is not a technicality: it is the difference between a few tens of thousands of comparisons a day and hundreds of millions, which directly affects response time for the user and the processing load on the company's servers.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Compare bubble sort and merge sort, and state one situation in which each would be the better choice.5 marks
Compare

Mark scheme0 / 5
  • LBubble sort repeatedly swaps adjacent items while merge sort divides and merges
  • LMerge sort is significantly faster on large lists
  • LBubble sort uses almost no extra memory because it sorts in place
  • LMerge sort requires additional memory to store the sub lists
  • LBubble sort is better on small or nearly sorted lists, merge sort on large lists where speed matters
Model answer

Bubble sort works by repeatedly comparing adjacent items and swapping any that are in the wrong order, continuing until a pass makes no swaps, whereas merge sort divides the list in half until each part holds one item and then merges the parts back together in order. On a large list merge sort is dramatically faster, because the number of steps grows roughly in proportion to n multiplied by the logarithm of n rather than n squared. The trade off is memory: bubble sort works in place and needs room for only a single temporary variable, while merge sort must hold the sub lists separately and so needs extra space roughly equal to the size of the original list. Bubble sort is therefore the better choice for a short list, or one that is already nearly in order, where its simplicity and low memory use matter more than raw speed, for example sorting a class of thirty test scores on a microcontroller. Merge sort is the better choice when a large volume of data must be sorted quickly and there is memory to spare, for example ordering a hundred thousand search results on a server.

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