A Level Computer Science · Chapter 25 · Component 02: Algorithms and programming
Finding and ordering data are the jobs computers do most, and the right algorithm can turn a task of hours into one of milliseconds.
This chapter teaches the two standard searches and the four standard sorts, tracing each by hand and counting the work it does. You will learn when each algorithm is the right choice, and how its cost grows as the data grows.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- describe, trace and write linear search and binary search
- state the precondition for binary search and find its worst-case number of comparisons
- trace bubble sort, insertion sort, merge sort and quick sort on a list, pass by pass
- count the comparisons each algorithm makes, and give its best-case and worst-case time complexity
- compare the algorithms' use of memory and their suitability for different data
- choose an appropriate searching or sorting algorithm for a given problem, and justify the choice
Time: three sessions, about 4 hours, plus the programming task.
You need first: arrays and iteration from Programming constructs, and recursion from Subroutines and recursion. Big O notation from Algorithm analysis and Big O notation helps, but this chapter explains what it needs.
The big picture
The big picture
Open a contacts app and type a name. The match appears before you lift your finger, even with thousands of contacts. Type a word into a search engine, and billions of pages are checked in under a second. Neither would be possible if the computer looked at every item in turn.
The trick is order. A phone book is sorted, so you never read it from the start. You open it near the middle, see whether you are too far, and jump again. Each jump throws away half of what is left. This is binary search, and it is one of the most powerful ideas in computing.
But order has a cost. Someone has to sort the data first, and sorting is harder than searching. Sorting a million items with a simple method might take a trillion comparisons. A better method needs about twenty million. On a laptop, that is the difference between days and a fraction of a second.
So the two problems are linked. If you search a list once, you might as well check every item. If you search it a thousand times, it pays to sort it first. Databases, file systems and search engines all make this choice.
This chapter studies the standard algorithms for both jobs. For searching, there are linear search and binary search. For sorting, there are bubble sort, insertion sort, merge sort and quick sort. Each has strengths, and each has a situation where it is the best choice.
To compare them fairly, we count the work each does. The usual measure is the number of comparisons between items. Counting by hand on small lists shows the pattern. Then Big O notation describes how the count grows as the list gets larger.
The aim is not to memorise code. It is to understand each algorithm so well that you can trace it on any list, write it from its idea, and argue about when to use it. Those are exactly the skills the exam tests.
Section 1
Linear search
The idea
Linear search is the simplest search there is. Start at the first item. Compare it with the target. If it matches, stop and report its position. If not, move to the next item. If you reach the end without a match, the target is not in the list.
Linear search works on any list, sorted or not. That is its great strength. It needs no preparation, and it works on data structures you can only read from the start, such as a linked list or a file.
Common mistake: thinking linear search needs a sorted list. Linear search checks every item in turn, so the order of the list makes no difference to whether it finds the target. Only binary search needs sorted data.
The algorithm
In pseudocode, linear search is a single loop. It returns the index of the target, or −1 if the target is absent. Returning −1 is a common convention, because −1 can never be a valid index.
function linearSearch(items, target)
for i = 0 to items.length - 1
if items[i] == target then
return i
endif
next i
return -1
endfunction
Notice that the function returns as soon as it finds a match. There is no need to check the rest of the list. The final return -1 runs only if the loop finishes without finding anything.
Worked example 1: tracing linear search
Trace a linear search for 27 in the list 14, 3, 27, 8, 19.
| Working | Reason |
|---|---|
| i = 0: 14 ≠ 27 | The first item does not match, so move on |
| i = 1: 3 ≠ 27 | The second item does not match either |
| i = 2: 27 = 27, return 2 | A match, so the search stops immediately |
| Result: index 2 after 3 comparisons | One comparison for each item inspected |
Best, worst and average cases
The number of comparisons depends on where the target is. If it is the first item, linear search needs one comparison: the best case. If it is the last item, or absent, it needs n comparisons for n items: the worst case.
If the target is present and equally likely to be anywhere, the average is (n + 1)/2. That is about half the list. Doubling the list doubles the average work, so the time grows in direct proportion to n. In Big O notation, linear search is O(n).
Common mistake: confusing best, average and worst cases. The best case of linear search is one comparison, but that is rarely useful for planning. When an algorithm is described by its complexity, the worst case is usually meant, because it is the guarantee.
Worked example 2: counting comparisons
A list holds 1,000 customer names in no particular order. Find the best, worst and average numbers of comparisons for a linear search.
| Working | Reason |
|---|---|
| Best case: 1 comparison | The target happens to be the first name |
| Worst case: 1000 comparisons | The target is last, or not in the list |
| Average: (1000 + 1)/2 = 500.5 comparisons | A present target is equally likely anywhere |
| Doubling to 2,000 names doubles each of these | Linear search is O(n) |
Searching records
Real lists rarely hold bare numbers. They hold records, such as customers or products, and the search compares one field of each record, called the key. A search for a customer by email address compares the email field of each record with the target.
Strings are compared character by character, using their character codes. So "Adams" comes before "Baker", and "Zoe" comes after "Adams". Upper and lower case have different codes, so a search often converts both strings to the same case first.
A faster linear search
A small trick speeds up linear search. The basic loop makes two tests on every item: has the end been reached, and is this the target? A sentinel removes the first test. The target is placed in an extra slot at the end, so the loop is certain to stop.
When the loop stops, the program checks whether it stopped at the sentinel. If so, the target was not really in the list. The number of comparisons with items is unchanged, so the algorithm is still O(n). Only the overhead of each step falls.
When linear search is right
Linear search is often the best choice. For a small list, it is fast enough, and simpler code has fewer bugs. For a list that changes often, keeping it sorted may cost more than searching it. And for a list searched only once, sorting first is a waste.
Linear search can also do jobs binary search cannot. It can find every match, not just one. It can search on any condition, such as "the first price over £50". It can search a list of items that cannot be put in order at all.
Check yourself. The target of a linear search is not among the 64 items in the list. How many comparisons are made, and why?
Show the answer
It makes 64 comparisons. When the target is absent, linear search must check every item before it can be sure, so the absent case is the worst case.
Section 2
Binary search
The idea
Binary search needs a sorted list. It compares the target with the middle item. If they match, the search is over. If the target is smaller, it must lie in the left half, so the right half is discarded. If larger, the left half is discarded. Then the search repeats on what remains.
Each comparison halves the part of the list still being searched. A list of 1,000 items becomes 500, then 250, 125, 62, 31, 15, 7, 3, 1. After about ten comparisons, only one item is left.
Common mistake: using binary search on an unsorted list. Binary search discards half the list on the assumption that the items are in order. On an unsorted list it can throw away the half that holds the target and wrongly report that it is absent.
The algorithm
Binary search keeps two indices, low and high, marking the part of the list still in play. The midpoint is mid = (low + high) DIV 2, where DIV is whole-number division. The loop continues while low ≤ high.
function binarySearch(items, target)
low = 0
high = items.length - 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
The updates mid + 1 and mid − 1 matter. The middle item has already been checked, so it is excluded from the next search. Without the + 1 and − 1, the loop could inspect the same item forever.
Common mistake: rounding the midpoint up. DIV rounds down, so (4 + 9) DIV 2 = 6, not 7. Rounding up still finds the target, but it inspects different items, so a trace will not match the expected answer.
Worked example 3: tracing binary search
Trace a binary search for 31 in the sorted list 3, 8, 12, 19, 27, 31, 40.
| Working | Reason |
|---|---|
| low = 0, high = 6, mid = (0 + 6) DIV 2 = 3 | Start with the whole list in play |
| items[3] = 19 < 31, so low = 3 + 1 = 4 | The target is larger, so discard the left half |
| low = 4, high = 6, mid = (4 + 6) DIV 2 = 5 | Search the right half only |
| items[5] = 31 = 31, return 5 | A match on the second comparison |
| Result: index 5 after 2 comparisons | Linear search would have needed six |
Worked example 4: a target that is absent
Trace a binary search for 10 in the same list.
| Working | Reason |
|---|---|
| mid = 3: items[3] = 19 > 10, so high = 2 | The target is smaller, so discard the right half |
| mid = (0 + 2) DIV 2 = 1: items[1] = 8 < 10, so low = 2 | The target is larger than 8 |
| mid = (2 + 2) DIV 2 = 2: items[2] = 12 > 10, so high = 1 | The target is smaller than 12 |
| low = 2 > high = 1, so return −1 | Nothing is left to search: 10 is absent |
| Result: −1 after 3 comparisons, inspecting 19, 8 and 12 | Three halvings reduce seven items to none |
The worst case
After k comparisons, at most n/2ᵏ items remain. The search must end once fewer than one item is left. So the worst case is the number of halvings needed to reach one item, plus the final comparison.
Derivation: the worst case of binary search
Each comparison at least halves the number of items still in play. After k comparisons, the number left is at most
The search can continue only while at least one item remains. The largest k for which one item is still left satisfies
One more comparison inspects that last item. So the worst case is
For 1,000 items, log₂ 1000 is about 9.97, so the worst case is 9 + 1 = 10 comparisons. For a million items it is 20.
This growth is called logarithmic, written O(log n). Doubling the list adds only one comparison. That is why binary search can search a billion items in about thirty steps. The price is the precondition: the list must be sorted, and it must stay sorted whenever items are added or removed. Binary search also needs direct access to any position, which an array gives but a linked list does not.
Figure 25.1 compares the two searches. Change the size of the list and the position of the target. Watch how the cost of linear search climbs, while binary search barely moves. Then switch on the wrong model.
Linear search against binary search
- Linear search, this target
- 45comparisons
- Binary search, this target
- 6comparisons
- Worst cases for this n
- 64 against 7
Common mistake: thinking binary search takes half the comparisons. Binary search does not halve the total work; it halves what is left at every step. For 1,000 items it needs at most 10 comparisons, not 500. Its cost grows as log₂ n, not n/2.
Why halving is so powerful
The power of binary search comes from repeated halving. Each comparison doubles the size of list that can be handled with one more step. Ten comparisons cover about a thousand items, twenty cover a million, and thirty cover a billion.
You might ask why the list is not split into three parts instead. Splitting into thirds needs two comparisons to decide which third holds the target. That is more work per step, and it gives no overall saving. Halving is the simplest and the most efficient choice.
The idea appears far beyond lists of numbers. A programmer hunting for the change that introduced a bug can test the version halfway through the history, then halve again. The number guessing game, "higher or lower", is binary search too. Any search where each answer rules out half the possibilities is logarithmic.
Binary search by recursion
Binary search can also be written recursively. The function calls itself on the half that might hold the target, passing new values of low and high. The base cases are a match, or low > high. Both versions make the same comparisons, but the iterative one uses less memory, because it needs no stack of calls.
Check yourself. For a sorted list of 100 items, what is the largest number of comparisons binary search can need?
Show the answer
It needs at most 7 comparisons. Since 2⁶ = 64 ≤ 100 < 128 = 2⁷, ⌊log₂ 100⌋ = 6, and one more comparison gives 6 + 1 = 7.
Section 3
Bubble sort
The idea
Bubble sort works through the list comparing each pair of neighbours. If a pair is in the wrong order, it swaps them. One complete run through the list is called a pass. The passes repeat until a pass makes no swaps at all.
During each pass, the largest unsorted item is carried along to the end, like a bubble rising through water. After the first pass, the largest item is in its final place. After the second, the two largest are, and so on.
The algorithm
The standard version uses a flag, often called swapped, to detect when the list is sorted. Each pass sets it to false, and any swap sets it to true. If a whole pass ends with the flag still false, nothing was out of order.
procedure bubbleSort(items)
n = items.length
do
swapped = false
for i = 0 to n - 2
if items[i] > items[i + 1] then
temp = items[i]
items[i] = items[i + 1]
items[i + 1] = temp
swapped = true
endif
next i
until swapped == false
endprocedure
A swap needs a temporary variable. Writing items[i] = items[i + 1] first would overwrite the original value of items[i], so both positions would end up holding the same item.
Common mistake: stopping bubble sort too early. The algorithm can stop only after a pass with no swaps. A pass that made a swap may have left another pair out of order, so one more pass is always needed to confirm the order.
Worked example 5: tracing bubble sort
Sort the list 5, 1, 4, 2, 8 with bubble sort. Count the comparisons and swaps.
| Working | Reason |
|---|---|
| Pass 1: 5,1 swap; 5,4 swap; 5,2 swap; 5,8 no swap | Four comparisons and three swaps |
| After pass 1: 1, 4, 2, 5, 8 | The largest item, 8, is now at the end |
| Pass 2: only 4,2 swaps, giving 1, 2, 4, 5, 8 | Four comparisons and one swap |
| Pass 3: no swaps, so stop | A pass with no swaps proves the list is sorted |
| Total: 12 comparisons and 4 swaps | Three passes of four comparisons each |
Figure 25.2 lets you step through the passes on different starting lists. Try a reversed list, and count how many passes it needs. Then switch on the wrong model to compare one real pass with what many students expect.
Bubble sort and insertion sort, step by step
- Comparisons so far
- 7
- Swaps in total
- 15
- Comparisons to finish
- 35
Common mistake: thinking one pass sorts the list. One pass carries the largest item to the end, but small items move left by only one place per pass. A small item at the far right needs many passes to reach the front.
Tracing bubble sort in an exam
Trace questions usually ask for the list after each pass, not after each swap. Work through one pass at a time on rough paper, comparing each pair from the left. Then write the list as it stands at the end of that pass, on its own line.
Keep a tally of comparisons and swaps if the question asks for them. A common check is that every pass of the basic version makes n − 1 comparisons. If your count for a pass is different, you have skipped a pair or compared one twice.
Making bubble sort faster
Two improvements are common. The first is the swapped flag, which stops as soon as the list is sorted. The second shortens each pass. After pass k, the last k items are in place, so the next pass can stop k places earlier.
Derivation: the comparisons in the improved bubble sort
On a list of n items in reverse order, every pass is needed. With shorter passes, the first makes n − 1 comparisons, the next n − 2, and so on down to 1.
Pairing the first term with the last, and so on, gives pairs that each total n. There are (n − 1)/2 such pairs.
The n² term dominates as n grows. So even the improved bubble sort makes about n²/2 comparisons in the worst case, which is O(n²).
Worked example 6: the worst case
Find the worst-case number of comparisons for the improved bubble sort on 6 items, and compare it with the basic version.
| Working | Reason |
|---|---|
| Improved: 5 + 4 + 3 + 2 + 1 = 15 comparisons | Each pass is one comparison shorter |
| Check: n(n − 1)/2 = 6 × 5/2 = 15 | The formula from the derivation agrees |
| Basic: 6 passes of 5 comparisons = 30 comparisons | Five swapping passes, then one to confirm |
| The improvement halves the work, but both are O(n²) | Halving does not change the growth rate |
Why study a slow algorithm?
Bubble sort is rarely used for real data, so why learn it? It shows the core ideas of sorting with nothing else in the way: comparing, swapping and repeating until done. It also makes a useful baseline, so that the gains of faster algorithms are clear.
Bubble sort is also a good first example of proving that an algorithm works. After pass k, the k largest items are in their final places. That fact, called an invariant, guarantees that the list is sorted after at most n − 1 passes.
Strengths and weaknesses
Bubble sort is easy to understand and to code. It sorts in place, needing no extra memory beyond one temporary variable. On a list that is already sorted, it finishes after one pass of n − 1 comparisons, so its best case is O(n).
But its worst and average cases are O(n²). Doubling the list makes it four times slower. For more than a few thousand items it is far too slow. It is mainly used for teaching, and for tiny or nearly sorted lists.
Check yourself. The list 2, 3, 4, 5, 1 is sorted by bubble sort with a swapped flag. How many passes are needed, and why so many?
Show the answer
It needs five passes. The small item 1 starts at the far right and moves left by only one place per pass. It needs four passes to reach the front, and a fifth pass confirms that no swaps remain.
Section 4
Insertion sort
The idea
Insertion sort works the way many people sort a hand of cards. The left part of the list is kept sorted. Each new item is taken from the unsorted part and inserted into its correct place among the sorted items. At the start, the sorted part is just the first item.
To insert an item, compare it with the sorted items to its left, moving from right to left. Each larger item shifts one place to the right to make room. When an item no larger than it is found, or the start of the list is reached, the new item drops into the gap.
The algorithm
The outer loop picks each item in turn from the second onwards. The inner loop shifts larger items right until the gap is in the right place.
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
The test items[j] > current uses a strict greater-than. Equal items are not shifted past each other, so they keep their original order. A sort with this property is called stable.
Common mistake: comparing against the whole sorted part. The inner loop stops as soon as it finds an item no larger than the current one. The sorted part is in order, so nothing further left can be larger. Counting comparisons with every sorted item overstates the work.
Worked example 7: tracing insertion sort
Sort 5, 1, 4, 2, 8 with insertion sort. Count the comparisons and shifts.
| Working | Reason |
|---|---|
| Insert 1: 5 > 1 shifts, start reached: 1, 5, 4, 2, 8 | One comparison and one shift |
| Insert 4: 5 shifts, 1 ≤ 4 stops: 1, 4, 5, 2, 8 | Two comparisons and one shift |
| Insert 2: 5 and 4 shift, 1 ≤ 2 stops: 1, 2, 4, 5, 8 | Three comparisons and two shifts |
| Insert 8: 5 ≤ 8 stops at once | One comparison and no shifts |
| Total: 7 comparisons and 4 shifts | Fewer comparisons than bubble sort's 12 |
Shifting, not swapping
Insertion sort moves items by shifting, not by swapping. Bubble sort swaps a pair with three assignments, using a temporary variable. Insertion sort holds the current item aside once, then each shift is a single assignment. This is one reason it runs faster than bubble sort with the same number of comparisons.
Insertion sort is also an online algorithm. It can sort items as they arrive, one at a time, without waiting for the whole list. Each new arrival is simply inserted into the sorted part. A high-score table that gains one score at a time works this way.
Best and worst cases
On a list that is already sorted, each new item needs only one comparison to find that it is already in place. So the best case is n − 1 comparisons, which is O(n). On a list in reverse order, each item must travel to the front, making 1 + 2 + … + (n − 1) comparisons.
That worst case is n(n − 1)/2, the same total as the improved bubble sort, so insertion sort is O(n²) too. But in practice it is usually faster. It does no swapping, only shifting, and it stops each inner loop early.
Nearly sorted data
Insertion sort shines on data that is nearly in order. Each item needs only a few comparisons to find its place. A list that is sorted except for one swapped pair costs barely more than one comparison per item.
This matters in real systems. A list that is kept sorted and gains a few new items at the end is nearly sorted. Insertion sort is also used inside faster algorithms to finish off small sublists, where its low overhead beats more complicated methods.
Check yourself. Insertion sort runs on the sorted list 1, 2, 3, 4, 5, 6, 7, 8. How many comparisons does it make in total?
Show the answer
It makes 7 comparisons. Each of the seven items after the first is compared once with its left neighbour, finds it smaller, and stays where it is. This is the best case, n − 1 comparisons.
Section 5
Merge sort
Divide and conquer
Merge sort uses a strategy called divide and conquer. It splits the problem into smaller problems, solves those, and combines the results. Here the list is split in half again and again until every part holds one item. A list of one item is already sorted.
Then the parts are merged back together in pairs. Merging two sorted lists into one sorted list is easy, and it is fast. Level by level, the sorted lists double in length until one sorted list remains.
The merge step
To merge two sorted lists, compare their first items. Move the smaller one into the result. Repeat with the new first items. When one list runs out, copy whatever remains of the other list to the end, with no more comparisons needed.
Common mistake: joining sublists without comparing. Merging is not placing one list after the other. Two sorted lists such as 2, 7 and 3, 5 joined end to end give 2, 7, 3, 5, which is not sorted. Each step compares the two front items and takes the smaller.
Worked example 8: merging two lists
Merge the sorted lists 3, 27, 38, 43 and 9, 10, 82. Count the comparisons.
| Working | Reason |
|---|---|
| 3 vs 9: take 3; 27 vs 9: take 9; 27 vs 10: take 10 | Each step takes the smaller front item |
| 27 vs 82: take 27; 38 vs 82: take 38; 43 vs 82: take 43 | The left list runs out after six comparisons |
| Copy the remaining 82 without comparing | Whatever is left is already in order |
| Result: 3, 9, 10, 27, 38, 43, 82 after 6 comparisons | Never more than one fewer than the total items |
Worked example 9: a full merge sort
Sort 38, 27, 43, 3, 9, 82, 10 with merge sort, merging neighbouring lists in pairs.
| Working | Reason |
|---|---|
| Split into seven single items | A one-item list is already sorted |
| Merge pairs: 27, 38 and 3, 43 and 9, 82, with 10 alone | Three merges of one comparison each |
| Merge again: 3, 27, 38, 43 and 9, 10, 82 | Three and two comparisons for these merges |
| Final merge: 3, 9, 10, 27, 38, 43, 82 | Six comparisons, as in worked example 8 |
| Total: 3 + 3 + 2 + 6 = 14 comparisons over 3 levels | About n comparisons per level |
Two ways to describe merge sort
Merge sort is usually written as a recursive function. It splits the list in half, calls itself on each half, and merges the two sorted halves it gets back. The base case is a list of one item, which is returned as it is.
Traced by hand, it is often shown bottom-up instead, as in worked example 9. Start from single items and merge neighbours level by level. Both descriptions do the same kind of merges and give the same sorted list. When the list length is not a power of two, they may pair items a little differently, so follow the method a question gives.
Why merge sort is fast
Each level of merging handles every item once, so it makes at most about n comparisons. The number of levels is the number of times n can be halved, which is about log₂ n. So the total work is about n × log₂ n.
This is written O(n log n), and it holds in the best, average and worst cases alike. For a million items, n log₂ n is about 20 million, compared with about 500 billion for n²/2. That is why merge sort can sort huge data sets that bubble sort never could.
Common mistake: thinking merge sort grows as n². Merge sort makes about n comparisons on each of about log₂ n levels, so its cost grows as n log₂ n. For 1,000 items that is about 10,000 comparisons, not 1,000,000.
Stability
A sort is stable if items with equal keys stay in their original order. Imagine sorting students by class, when they are already in alphabetical order. A stable sort keeps the students within each class in alphabetical order. An unstable sort may jumble them.
Merge sort is stable when the merge takes the left item on a tie, using ≤ rather than <. Insertion sort and bubble sort are stable too, because they never move an item past an equal one. Quick sort, partitioning in place, is usually not stable.
The cost in memory
Merge sort has a price. Merging needs somewhere to put the result, so a typical version uses extra memory equal to the size of the list. Sorting a list of a gigabyte needs another gigabyte of working space. Bubble sort and insertion sort need almost none.
Merge sort is also naturally recursive, so it uses stack space for its calls. But it is stable, and it works well on data too large for memory. Sorted chunks can be merged straight from files, which is how very large data sets are sorted.
Check yourself. How many levels of merging does merge sort need for a list of 16 items, and how many items are in each list after the second level?
Show the answer
It needs 4 levels, because 16 = 2⁴ and each level halves the number of lists. After the first level the lists hold 2 items, and after the second they hold 4.
Section 6
Quick sort and choosing an algorithm
The idea
Quick sort also divides and conquers, but it does the hard work before dividing. It chooses one item, the pivot. It then partitions the list: items smaller than the pivot go to its left, and the rest go to its right. The pivot is now in its final place.
Then quick sort sorts the left part and the right part in the same way, recursively. A part with fewer than two items is already sorted. No merging is needed, because every item on the left is smaller than every item on the right.
Partitioning
There are several ways to partition. In this chapter the first item is the pivot. Each other item is compared with it once and placed in the smaller list or the other list, keeping its order. Exam questions say which method to use, so always follow the method given.
Real implementations partition in place, swapping items within the list using two pointers. This avoids extra memory, but the items end up in a different order within each side. The pivots chosen, and the total number of comparisons, follow the same pattern.
Worked example 10: tracing quick sort
Sort 5, 3, 8, 1, 9, 2 with quick sort, using the first item of each part as the pivot.
| Working | Reason |
|---|---|
| Pivot 5: left 3, 1, 2; right 8, 9 | Five comparisons with the pivot |
| Pivot 3 on 3, 1, 2: left 1, 2; right empty | Two comparisons, one for each other item |
| Pivot 1 on 1, 2: right 2; pivot 8 on 8, 9: right 9 | One comparison in each of these partitions |
| Sorted: 1, 2, 3, 5, 8, 9 after 5 + 2 + 1 + 1 = 9 comparisons | Single items and empty parts need no work |
Best and worst cases
When each pivot splits its part into two halves, quick sort has about log₂ n levels with about n comparisons each. That gives O(n log n), like merge sort. On random data this is what usually happens, and quick sort is often the fastest sort in practice.
But a bad pivot ruins it. If the list is already sorted and the first item is the pivot, every partition puts nothing on the left. Each level removes only one item, so the comparisons total n(n − 1)/2. The worst case is O(n²).
Common mistake: assuming quick sort is always fast. With the first item as pivot, a sorted or reversed list makes every partition lopsided, and quick sort slows to O(n²). Choosing the middle item, or a random one, as pivot avoids this in practice.
Choosing a pivot
The pivot decides how well quick sort performs. The ideal pivot is the median, which splits a part into two equal halves. Finding the true median takes extra work, so practical versions estimate it. A common choice is the median of the first, middle and last items.
Another choice is a random item. Then no particular input is always bad, and the chance of many poor pivots in a row is tiny. With either choice, quick sort runs in O(n log n) time on almost every input it meets.
Comparing the algorithms
The table below summarises the four sorts. Bubble sort and insertion sort are simple, sort in place and are O(n²). Merge sort and quick sort are O(n log n) on typical data, which is vastly faster for large lists.
| Algorithm | Best case | Worst case | Extra memory |
|---|---|---|---|
| Bubble sort, with flag | O(n) | O(n²) | O(1), in place |
| Insertion sort | O(n) | O(n²) | O(1), in place |
| Merge sort | O(n log n) | O(n log n) | O(n) |
| Quick sort | O(n log n) | O(n²) | O(log n) for the recursion |
Common mistake: ignoring the memory merge sort needs. Merge sort's guaranteed speed comes at the cost of extra memory as large as the list. On a device with little memory, an in-place sort may be the better choice even though it is slower.
Making a choice
Choose by the data and the situation. For a handful of items, or data that is nearly sorted, insertion sort is simple and fast. For large data where a guarantee matters, merge sort is safe. For large data in memory, a well-pivoted quick sort is usually quickest.
Real libraries combine the ideas. Python's built-in sort is a hybrid of merge sort and insertion sort. It finds runs that are already in order and merges them, using insertion sort on short stretches. So it is O(n log n) in the worst case and close to O(n) on nearly sorted data.
For searching, sort only if it pays. One search of an unsorted list costs n comparisons. Sorting costs about n log₂ n. If the list will be searched many times, the sort is soon repaid by fast binary searches.
Check yourself. An O(n²) sort takes 2 seconds for 1,000 items. Estimate its time for 4,000 items.
Show the answer
The list is 4 times longer, and for O(n²) the time grows by 4² = 16. So the estimate is 2 × 16 = 32 seconds.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Linear search | Check each item in turn from the start | Works on unsorted lists | Worst case n comparisons, O(n) |
| Binary search | Compare with the middle item and discard half | Needs a sorted list | Worst case ⌊log₂ n⌋ + 1, O(log n) |
| Midpoint | mid = (low + high) DIV 2 | (4 + 9) DIV 2 = 6 | DIV rounds down |
| Bubble sort | Swap neighbours in the wrong order, pass after pass | Stops after a pass with no swaps | Best O(n), worst O(n²) |
| Insertion sort | Insert each item into a growing sorted part | Fast on nearly sorted data | Best O(n), worst O(n²) |
| Merge sort | Split into single items, then merge in pairs | Merge by taking the smaller front item | O(n log n) always, O(n) memory |
| Quick sort | Partition around a pivot, then sort each side | First item as pivot | Average O(n log n), worst O(n²) |
| Stable sort | Equal items keep their original order | Insertion sort and merge sort | Matters when sorting records by one field |
| In place | Sorts within the list, with little extra memory | Bubble sort and insertion sort | Extra memory O(1) |
Programming task
Programming task: counting comparisons
Aim
Write binary search and insertion sort in Python, each with a counter for the comparisons it makes. Test them on chosen lists, and check the counts against the best and worst cases from this chapter.
Design
Each function returns two values: its usual result and the comparison count. Binary search returns the index found, or −1, and counts one comparison for each item it inspects. Insertion sort returns the sorted list, and counts one comparison each time it compares the current item with a sorted item.
The tests cover a found target, the first item, an absent target and an empty list for the search. For the sort they cover a mixed list, the best case and the worst case. Each expected output is worked out by hand before running the program.
Code
def binary_search(items, target):
"""Return (index, comparisons); index is -1 if target is absent. items must be sorted."""
low, high = 0, len(items) - 1
comparisons = 0
while low <= high:
mid = (low + high) // 2
comparisons += 1 # one comparison for each item inspected
if items[mid] == target:
return mid, comparisons
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1, comparisons
def insertion_sort(items):
"""Return (sorted copy, comparisons) without changing the original list."""
result = list(items)
comparisons = 0
for i in range(1, len(result)):
current = result[i]
j = i - 1
while j >= 0:
comparisons += 1
if result[j] <= current:
break
result[j + 1] = result[j]
j -= 1
result[j + 1] = current
return result, comparisons
print(binary_search([3, 8, 12, 19, 27, 31, 40], 31))
print(insertion_sort([5, 1, 4, 2, 8]))
Python's // operator is whole-number division, the same as DIV. The break leaves the inner loop as soon as a smaller item is found, which is what makes the best case fast.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | binary_search([3, 8, 12, 19, 27, 31, 40], 31) | (5, 2) | A target found after one halving |
| 2 | binary_search([3, 8, 12, 19, 27, 31, 40], 3) | (0, 3) | The first item, at the far edge |
| 3 | binary_search([3, 8, 12, 19, 27, 31, 40], 10) | (−1, 3) | An absent target, the worst case |
| 4 | binary_search([], 5) | (−1, 0) | An empty list must not crash |
| 5 | insertion_sort([5, 1, 4, 2, 8]) | ([1, 2, 4, 5, 8], 7) | A mixed list, matching worked example 7 |
| 6 | insertion_sort([1, 2, 3, 4]) | ([1, 2, 3, 4], 3) | The best case: n − 1 comparisons |
| 7 | insertion_sort([4, 3, 2, 1]) | ([1, 2, 3, 4], 6) | The worst case: n(n − 1)/2 comparisons |
Evaluation
The counts match the theory: three comparisons is the worst case for seven items, and the sort's best and worst cases match n − 1 and n(n − 1)/2. The empty-list test matters, because high starts at −1 and the loop must not run at all.
Counting comparisons is a fair measure of work that does not depend on the computer's speed. An improvement would run each function on lists of growing size and plot the counts, to see the log n and n² shapes directly.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State the condition a list must meet before binary search can be used on it.
Worked solution to Q1
The list must be sorted. Binary search discards half of the list after each comparison, which is only safe if the items are in order.
Q2. Give the worst-case number of comparisons for a linear search of 50 items, and say when it happens.
Worked solution to Q2
The worst case is 50 comparisons. It happens when the target is the last item, or is not in the list at all, so every item must be checked.
Q3. Name the sort that builds a sorted part at the left of the list, and give the time complexity of merge sort.
Worked solution to Q3
Insertion sort builds a sorted part at the left, inserting one item at a time. Merge sort is O(n log n) in every case, because it has about log₂ n levels of about n comparisons each.
Rung 2: Application
Q4. Trace a binary search for 47 in the sorted list 2, 5, 9, 14, 21, 30, 38, 47, 55, 63. List the items inspected.
Worked solution to Q4
First mid = (0 + 9) DIV 2 = 4, so 21 is inspected; 21 < 47, so low = 5. Then mid = (5 + 9) DIV 2 = 7, and the item there is 47. The items inspected are 21, then 47, found at index 7.
Q5. Give the list 6, 2, 9, 4, 1 after the first pass of bubble sort.
Worked solution to Q5
The pass compares 6,2 (swap), 6,9 (no swap), 9,4 (swap) and 9,1 (swap). The largest item, 9, ends at the right. After the first pass the list is 2, 6, 4, 1, 9.
Q6. Sort 6, 2, 9, 4, 1 with insertion sort. Give the list after each insertion and the total comparisons.
Worked solution to Q6
After inserting 2 the list is 2, 6, 9, 4, 1. Inserting 9 changes nothing, because 9 is larger than 6. After inserting 4 it is 2, 4, 6, 9, 1, and after inserting 1 it is 1, 2, 4, 6, 9. The insertions make 1, 1, 3 and 4 comparisons, a total of 9.
Q7. Merge the sorted lists 1, 4, 7, 8 and 2, 3, 5, 6. How many comparisons does the merge make?
Worked solution to Q7
Compare front items and take the smaller each time: 1, 2, 3, 4, 5, 6. That takes six comparisons. The right list is then empty, so 7 and 8 are copied without comparing. The merge makes 6 comparisons.
Rung 3: Analysis
Q8. A database index holds 2,000,000 sorted keys. Find the worst-case number of comparisons for a binary search.
Worked solution to Q8
Find the largest power of 2 that is no more than the number of keys. Since 2²⁰ = 1,048,576 ≤ 2,000,000 < 2²¹, ⌊log₂ 2,000,000⌋ = 20. Adding the final comparison, the worst case is 20 + 1 = 21 comparisons, against 2,000,000 for a linear search.
Q9. Quick sort, with the first item of each part as pivot, sorts 7, 2, 9, 4, 1, 8. Give the pivots in order and the total comparisons.
Worked solution to Q9
Pivot 7 splits into 2, 4, 1 and 9, 8 after five comparisons. Pivot 2 splits 2, 4, 1 into 1 and 4 after two. Pivot 9 leaves 8 on its left after one. The pivots are 7, 2 and 9, making 8 comparisons.
Q10. Compare the comparisons made by insertion sort and by basic bubble sort, with a flag, on the nearly sorted list 1, 2, 4, 3, 5, 6.
Worked solution to Q10
Insertion sort makes one comparison per item except for 3, which needs two: 6 comparisons in total. Bubble sort needs one pass to swap 4 and 3, then a second to confirm, so 2 × 5 = 10 comparisons. Insertion sort does less work on nearly sorted data.
Q11. A program's O(n²) sort takes 0.5 seconds for 2,000 items. Estimate its time for 6,000 items, and say what an O(n log n) sort would need for the same growth.
Worked solution to Q11
The list is 3 times longer, so an O(n²) sort takes 3² = 9 times as long: 0.5 × 9 = 4.5 seconds. An O(n log n) sort grows only a little faster than n, so it would take a little over 3 times as long.
Rung 4: Stretch
Q12. Using the first item as its pivot, quick sort is given the already sorted list 1, 2, 3, 4, 5, 6. Count the comparisons and explain what this shows.
Worked solution to Q12
Every partition puts nothing on the left, so the parts shrink by one each time. The comparisons are 5 + 4 + 3 + 2 + 1 = 15, which is n(n − 1)/2. This is quick sort's O(n²) worst case, caused by a poor choice of pivot.
Q13. Merge sort sorts 8, 4, 7, 1, 6, 2, 5, 3. Find the number of merge levels and the total comparisons, and compare with the improved bubble sort's worst case.
Worked solution to Q13
Eight items need log₂ 8 = 3 levels. The merges make 4, then 6, then 6 comparisons, a total of 16. The improved bubble sort's worst case for 8 items is 8 × 7/2 = 28 comparisons, so merge sort does far less work.
Q14. A list holds 10,000 names. Explain whether it is worth sorting it with merge sort before making 20 searches, using worst-case comparison counts.
Worked solution to Q14
Twenty linear searches could need 20 × 10,000 = 200,000 comparisons. Merge sort needs about n log₂ n ≈ 10,000 × 14 = 140,000, and 20 binary searches need at most 20 × 14 = 280 more. So sorting first costs about 140,280, which is only a little cheaper. With more searches, sorting first wins by far more.
Exam practice
Exam technique and worked answer workshop
Trace questions are marked line by line. Set out each pass or each comparison on its own line, in the order the algorithm does it. Use the method the question names, such as the first item as pivot, or mid = (low + high) DIV 2.
When writing algorithms, examiners look for the key steps rather than exact syntax. A loop, a comparison, a return of the index and a return of −1 earn the marks for linear search. Use meaningful names and indent consistently, so the logic is easy to follow.
In comparison questions, name the complexities and explain them. Say what happens as n grows, mention best and worst cases, and consider memory. Then make a justified choice for the situation given, because the final judgement usually carries marks.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
Write a function linearSearch(names, target) that returns the index of target in the array names, or −1 if target is not present.
Mark scheme for exam question 1
- B1 a loop through every index of names, from 0 to the last
- B1 each item compared with target
- B1 the index returned as soon as a match is found
- B1 −1 returned only after the loop has checked every item
Exam question 2 (5 marks · Paper 02 · about 6 minutes)
A sorted array holds 4, 9, 15, 22, 28, 35, 41, 50, 57.
(a) State why binary search can be used on this array. [1]
(b) Trace a binary search for 41, giving each item compared with the target. [2]
(c) State the greatest number of comparisons binary search could need on this array. [1]
(d) Explain why binary search needs fewer comparisons than linear search on large arrays. [1]
Mark scheme for exam question 2
- B1 the array is sorted
- M1 first midpoint (0 + 8) DIV 2 = 4, so 28 is compared and the search moves right
- A1 second midpoint (5 + 8) DIV 2 = 6, so 41 is compared and found: 28, then 41
- B1 4 comparisons
- B1 each comparison halves the items left, so the work grows as log₂ n rather than n
Exam question 3 (4 marks · Paper 02 · about 5 minutes)
Bubble sort with a swapped flag sorts the array 6, 2, 9, 4, 1 into ascending order.
(a) Give the array after the first pass. [2]
(b) State how many passes are made in total. [1]
(c) Explain how the algorithm knows when to stop. [1]
Mark scheme for exam question 3
- M1 neighbouring pairs compared and swapped when out of order, with 9 carried to the end
- A1 2, 6, 4, 1, 9
- B1 5 passes
- B1 it stops after a pass in which no swaps are made, shown by the flag staying false
Exam question 4 (5 marks · Paper 02 · about 6 minutes)
Insertion sort sorts the array 12, 5, 8, 3 into ascending order.
(a) Show the array after each item is inserted. [3]
(b) State the total number of comparisons made. [1]
(c) State the best-case time complexity of insertion sort, and the data that gives it. [1]
Mark scheme for exam question 4
- B1 after inserting 5: 5, 12, 8, 3
- B1 after inserting 8: 5, 8, 12, 3
- B1 after inserting 3: 3, 5, 8, 12
- B1 6 comparisons
- B1 O(n), when the data is already sorted
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
A company must sort one million customer records by surname every night. Discuss whether it should use bubble sort or merge sort. Refer to time complexity, memory and the nature of the data.
Mark scheme for exam question 5
Level 3 (5–6 marks): a thorough comparison of both algorithms' time complexity, with their best and worst cases. It explains what the difference means for a million records and considers memory. The answer reaches a justified recommendation and is well organised, with accurate terms.
Level 2 (3–4 marks): a correct comparison of complexity with some explanation, but memory or the context is treated briefly. A recommendation may be given without full justification.
Level 1 (1–2 marks): some relevant points, such as one algorithm's complexity, with little comparison or explanation. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- bubble sort is O(n²) in the worst and average cases
- merge sort is O(n log n) in every case
- for a million records, n² is about 10¹², but n log₂ n is about 2 × 10⁷
- bubble sort would take far too long; merge sort finishes quickly
- bubble sort's best case is O(n), on data that is already sorted
- if the records are nearly sorted each night, bubble or insertion sort could be fast
- merge sort needs extra memory as large as the data set
- merge sort is stable, so records with the same surname keep their order
- recommendation: merge sort, unless memory is very limited
Annotated model answer: exam question 5
"Bubble sort compares neighbouring records and swaps them, pass after pass. Its worst and average cases are O(n²). Merge sort splits the list into single records and merges them in pairs, and it is O(n log n) in every case." (Both algorithms and their complexities.)
"For a million records, n² is about 10¹² comparisons, while n log₂ n is only about 2 × 10⁷. So merge sort does about fifty thousand times less work, and would finish in seconds where bubble sort could take days." (What the complexities mean for this data.)
"Bubble sort's best case is O(n) on sorted data. If most records are already in order each night, it would be faster than its worst case suggests. But new customers arrive in any order, so this cannot be relied on." (Best case and the nature of the data.)
"Merge sort needs extra memory equal to the size of the data, while bubble sort sorts in place. A server sorting a million records will normally have this memory. Merge sort is also stable, keeping customers with the same surname in their original order." (Memory and stability.)
"So the company should use merge sort. Its guaranteed O(n log n) time outweighs its memory cost." (A justified recommendation.)
This answer reaches Level 3 and scores 6 marks. It compares, applies the figures to the context, and ends with a clear judgement.
Exam question 6 (5 marks · Paper 02 · about 7 minutes)
Quick sort sorts 7, 2, 9, 4, 1, 8, choosing the first item of each part as the pivot.
(a) Give the two parts produced by the first partition. [2]
(b) Give the pivots chosen, in order. [1]
(c) Explain why an already sorted list is the worst case for this version of quick sort, and give its time complexity. [2]
Mark scheme for exam question 6
- M1 7 chosen as the first pivot, with each other item compared with it
- A1 left part 2, 4, 1 and right part 9, 8
- B1 pivots 7, 2, 9
- B1 every partition puts no items on one side, so each level removes only the pivot
- B1 O(n²)
Exam question 7 (5 marks · Paper 01 · about 7 minutes)
An online shop's database holds 2,000,000 customer records. An index stores the customer IDs in sorted order.
(a) State the worst-case number of comparisons to find a record by linear search. [1]
(b) Calculate the worst-case number of comparisons for a binary search of the index. [2]
(c) Explain one cost of keeping the index sorted. [2]
Mark scheme for exam question 7
- B1 2,000,000 comparisons
- M1 ⌊log₂ 2,000,000⌋ = 20, since 2²⁰ ≤ 2,000,000 < 2²¹
- A1 21 comparisons
- B1 each new record's ID must be inserted in its correct place in the index
- B1 this takes extra time on every insertion, and the index needs extra storage
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
Write a function merge(left, right) that takes two arrays, each sorted in ascending order, and returns one array containing all their items in ascending order.
Mark scheme for exam question 8
- B1 an empty result array and an index for each input array, starting at 0
- M1 a loop that continues while both arrays have items left
- M1 the front items compared, with the smaller one added to the result
- A1 the index of the array taken from moved on by one
- B1 the remaining items of whichever array is not empty added to the result
- B1 the result array returned
Annotated model answer: exam question 8
function merge(left, right)
result = []
i = 0
j = 0
while i < left.length AND j < right.length
if left[i] <= right[j] then
result.append(left[i])
i = i + 1
else
result.append(right[j])
j = j + 1
endif
endwhile
while i < left.length
result.append(left[i])
i = i + 1
endwhile
while j < right.length
result.append(right[j])
j = j + 1
endwhile
return result
endfunction
The empty result and the two indices earn the first B mark. The loop with both conditions earns the first M mark, and comparing the front items earns the second. Moving on only the index that was used earns the A mark. The two final loops copy what remains, and returning the result earns the last mark. Using <= keeps the merge stable.
Connections
Synoptic link
The algorithms here underpin many other chapters. Their costs are measured with the tools of Algorithm analysis and Big O notation, which explains why O(n log n) beats O(n²). They run on the arrays of Arrays, records, stacks and queues, and merge sort and quick sort are classic examples from Subroutines and recursion.
Databases depend on them too. Databases and normalisation describes indexes, which are kept sorted so that records can be found by binary search. Graph traversal and shortest paths builds on the same habits of tracing and counting work.
Synoptic question 1. A list of 1,000 unsorted names will be searched 500 times. Compare the total comparisons for 500 linear searches, on average, with merge sorting once and then making 500 binary searches, using their worst cases.
Answer to synoptic question 1
Linear search averages (1000 + 1)/2 = 500.5 comparisons, so 500 searches make about 250,250. Merge sort makes about n log₂ n ≈ 1000 × 10 = 10,000 comparisons. Then 500 binary searches of at most 10 comparisons make 5,000. The total is about 15,000, so sorting first is far cheaper.
Recap
Recap and next step
- Linear search checks each item in turn; it works on any list and is O(n).
- Binary search needs a sorted list, uses mid = (low + high) DIV 2, and needs at most ⌊log₂ n⌋ + 1 comparisons, so it is O(log n).
- Bubble sort swaps neighbours pass after pass and stops after a pass with no swaps; it is O(n²), with a best case of O(n).
- Insertion sort inserts each item into a growing sorted part; it is O(n²) but fast on nearly sorted data.
- Merge sort splits to single items and merges in pairs; it is always O(n log n) but needs O(n) extra memory.
- Quick sort partitions around a pivot; it is O(n log n) on average, but O(n²) when the pivots are poor, such as the first item of a sorted list.
Next chapter: Graph traversal and shortest paths applies the same tracing skills to depth-first search, breadth-first search, Dijkstra's algorithm and A*.
For your exam board
OCR A Level Computer Science (H446): this chapter covers the standard searching and sorting algorithms in section 2.3.1, Algorithms, in Component 02, Algorithms and programming: linear search, binary search, bubble sort, insertion sort, merge sort and quick sort, with their complexities.
AQA A Level Computer Science (7517): the fundamentals of algorithms section requires linear search, binary search and binary tree search, and bubble sort and merge sort, assessed on Paper 1. Insertion sort and quick sort are not required by AQA, but they deepen understanding of sorting.