UNIT 2 • MODULE 1 • LESSON 07
How do you find a word in a dictionary? You do not start at “aardvark” and read every entry. You open somewhere near the middle, see whether your word comes before or after that page, and throw away the half you do not need. Repeat a few times and you are there. Now imagine your friend has written words on cards and shuffled them. With no order to help you, the only option is to turn the cards over one at a time.
Those two strategies are the two searches in the CAPE syllabus: binary search (the dictionary method) and linear search (the shuffled-cards method). In this lesson you will write both as algorithms and in C, trace them step by step, count their comparisons, and learn when each one is the right choice.
What you will learn
- How linear search works, in pseudocode and in C, and how to count its comparisons.
- How binary search works using low, high and mid, and why the data must be sorted.
- How to trace both searches on a given array, including when the item is missing.
- How to compare the two searches: best case, worst case and typical case.
- Which search to choose for a given situation, including linked lists and unsorted data.
Part 1: Linear search
A linear search (also called a sequential search) starts at the first item and compares each item with the target, one after another, until it either finds the target or runs out of items. It makes no assumptions about the order of the data, so it works on any list.
FUNCTION linearSearch(list, n, key)
FOR i ← 0 TO n - 1
IF list[i] = key THEN
RETURN i
ENDIF
ENDFOR
RETURN -1
END FUNCTION
The function returns the index where the key was found, or -1 if it is not in the list. Returning straight away when the key is found is important: there is no need to keep looking. A common variation uses a WHILE loop and a Boolean found flag, which some teachers prefer because it has only one exit point:
i ← 0
found ← FALSE
WHILE i < n AND found = FALSE DO
IF list[i] = key THEN
found ← TRUE
ELSE
i ← i + 1
ENDIF
ENDWHILE
Counting comparisons
| Case | When it happens | Comparisons (n items) |
| Best | The key is the first item | 1 |
| Worst | The key is last, or not in the list | n |
| Average (key present) | The key is equally likely to be anywhere | about n / 2 |
Worked example 1: linear search in C
This function receives the array, its length and the key, and also reports how many comparisons it made through a pointer parameter. main searches for a value at the very start, one in the middle and one that is missing.
#include <stdio.h>
#define N 8
int linearSearch(const int a[], int n,
int key, int *comps)
{
int i;
*comps = 0;
for (i = 0; i < n; i++) {
(*comps)++;
if (a[i] == key)
return i;
}
return -1;
}
int main(void)
{
int marks[N] = {64, 12, 89, 45,
70, 33, 91, 58};
int keys[3] = {64, 33, 50};
int k, pos, comps;
for (k = 0; k < 3; k++) {
pos = linearSearch(marks, N,
keys[k], &comps);
if (pos == -1)
printf("%d missing", keys[k]);
else
printf("%d at index %d",
keys[k], pos);
printf(", comparisons: %d\n",
comps);
}
return 0;
}
Output:
64 at index 0, comparisons: 1 33 at index 5, comparisons: 6 50 missing, comparisons: 8
The output matches the table exactly. 64 is first (best case, one comparison). 33 is at index 5, so six comparisons. 50 is missing, so every one of the eight items is checked (worst case) before the function returns -1.
Part 2: Binary search
A binary search works only on a sorted list. It keeps track of the part of the list that could still contain the key, using two indexes, low and high. Each step it looks at the item in the middle of that range:
- If the middle item is the key, the search is over.
- If the middle item is smaller than the key, the key can only be in the upper half, so move low to mid + 1.
- If the middle item is larger than the key, the key can only be in the lower half, so move high to mid – 1.
- If low passes high, the range is empty and the key is not in the list.
FUNCTION binarySearch(list, n, key)
low ← 0
high ← n - 1
WHILE low ≤ high DO
mid ← (low + high) DIV 2
IF list[mid] = key THEN
RETURN mid
ELSE IF list[mid] < key THEN
low ← mid + 1
ELSE
high ← mid - 1
ENDIF
ENDWHILE
RETURN -1
END FUNCTION
Because every comparison throws away half of what is left, binary search is described as a divide and conquer algorithm. The number of comparisons grows very slowly: a list of 15 items needs at most 4 comparisons, 1,000 items at most 10, and a million items at most 20. Each doubling of the list adds just one more comparison.
| Items (n) | Linear search, worst case | Binary search, worst case |
| 15 | 15 | 4 |
| 100 | 100 | 7 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
Worked example 2: binary search in C, with a trace
This version prints low, high and mid every time round the loop, so the output is a ready-made trace table. It searches for 63 (present) and 20 (missing) in a sorted array of 11 items.
#include <stdio.h>
#define N 11
int binarySearch(const int a[], int n,
int key)
{
int low = 0, high = n - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
printf(" low=%d high=%d mid=%d"
" a[mid]=%d\n",
low, high, mid, a[mid]);
if (a[mid] == key)
return mid;
if (a[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void)
{
int a[N] = {3, 8, 14, 21, 27, 35,
42, 50, 63, 77, 88};
int pos;
printf("Search for 63:\n");
pos = binarySearch(a, N, 63);
printf("Result: index %d\n", pos);
printf("Search for 20:\n");
pos = binarySearch(a, N, 20);
printf("Result: %d (not found)\n", pos);
return 0;
}
Output:
Search for 63: low=0 high=10 mid=5 a[mid]=35 low=6 high=10 mid=8 a[mid]=63 Result: index 8 Search for 20: low=0 high=10 mid=5 a[mid]=35 low=0 high=4 mid=2 a[mid]=14 low=3 high=4 mid=3 a[mid]=21 Result: -1 (not found)
Finding 63 takes two comparisons: 35 is too small, so low jumps to 6; then mid is 8 and a[8] is 63. Searching for 20 takes three: 35 is too big (high becomes 4), 14 is too small (low becomes 3), 21 is too big (high becomes 2). Now low (3) is greater than high (2), so the loop ends and -1 is returned. Notice mid = (low + high) / 2 uses whole-number division in C, which rounds down.
Part 3: Race them
The Try it runs both searches side by side on the same 15 numbers. Choose a target, then step. Linear search highlights the item it is checking; binary search shades the range that is still possible and outlines mid. Try the challenges to discover when each search wins.
Try it 1Search race: linear vs binary
Choose a target and step both searches together. Complete the four challenges.
Target
Linear search
Binary search
Did you see binary search fail on the unsorted data? It compared the target with the middle item, decided which half to throw away, and threw away the half that actually contained the target. Binary search does not crash on unsorted data; it quietly gives the wrong answer. That is why “the list must be sorted” is the first thing to say about it.
Part 4: Tracing searches by hand
For linear search, list each index checked until you stop. For binary search, use a table with columns low, high, mid, list[mid] and the decision. Here is a search for 27 in the 11-item array from Worked example 2:
| Step | low | high | mid | a[mid] | Decision |
| 1 | 0 | 10 | 5 | 35 | 35 > 27, so high ← 4 |
| 2 | 0 | 4 | 2 | 14 | 14 < 27, so low ← 3 |
| 3 | 3 | 4 | 3 | 21 | 21 < 27, so low ← 4 |
| 4 | 4 | 4 | 4 | 27 | Found at index 4 |
Four comparisons for 11 items is the worst case here. Now step through both searches in the tracer, answering the questions as you go.
Try it 2Trace linear and binary search
Choose a search, then step through it. Predict each value before you reveal it.
Output
Part 5: Choosing a search
| Question | Linear search | Binary search |
| Does the data need to be sorted? | No | Yes |
| Works on a linked list? | Yes | Not efficiently (no direct access to the middle) |
| Best case | 1 comparison (first item) | 1 comparison (middle item) |
| Worst case for n items | n comparisons | about log₂ n + 1 comparisons |
| Good for | Small or unsorted lists, lists searched once | Large sorted arrays searched many times |
| Code | Very simple | A little more complex (low, high, mid) |
Examiners like to ask what is true of both searches. Both can be used on a sorted list (linear search does not care about order, so sorted data is fine). Both return a position or a "not found" signal. But only linear search may need to examine every item in its worst case; binary search only ever examines a handful of middles. Be precise with words like both, always and require.
What if the data is unsorted but you need to search it thousands of times? Then it can be worth sorting it once (Lessons 08 and 09) and then using binary search for every look-up. That trade-off, paying once to save many times, is a big idea in computer science.
Duplicates
Neither search is broken by duplicate values. Linear search returns the first match it meets. Binary search returns a match, but not necessarily the first one, because it lands on whichever copy happens to be at a mid. If you need the first copy, you can keep searching to the left after a match.
Part 6: Searching records and strings
In real programs you rarely search for a bare number. You search for a student by ID, a product by code or a contact by name. The algorithms do not change; only the comparison does. To search an array of structs for a matching ID, compare one field:
FOR i ← 0 TO n - 1
IF students[i].id = targetId THEN
RETURN i
ENDIF
ENDFOR
RETURN -1
Strings need one extra step in C, because == compares the addresses of two strings, not their letters. Use strcmp from string.h, which returns 0 when two strings match, a negative number when the first comes earlier in alphabetical order, and a positive number when it comes later. That three-way answer is exactly what binary search needs:
cmp = strcmp(names[mid], key);
if (cmp == 0)
return mid;
else if (cmp < 0)
low = mid + 1;
else
high = mid - 1;
For binary search on names, the array must be in alphabetical order, and capital and small letters must be handled consistently, because strcmp compares character codes and every capital letter comes before every small letter. A school system might store all surnames in capitals for exactly this reason.
Efficiency in plain words
Computer scientists describe how the work grows as the data grows. For linear search, doubling the list doubles the worst-case work: the growth is linear. For binary search, doubling the list adds just one comparison: the growth is logarithmic. With small lists the difference hardly matters, and linear search may even be quicker because it is so simple. With large lists the difference is enormous: searching a sorted list of every person in the Caribbean, roughly 44 million people, takes at most 26 comparisons with binary search, against up to 44 million with linear search. That single example is worth remembering for any "compare the two searches" question.
Common mistakes
- Putting
return -1;inside the linear search loop, so the function gives up after checking only the first item. - Writing
while (low < high)instead oflow <= highin binary search, which skips the last remaining item and can miss the key. - Setting
low = midorhigh = midinstead of mid + 1 or mid - 1. The range may stop shrinking and the loop can run forever. - Using binary search on data that was never sorted, or was sorted in descending order while the code assumes ascending order.
- Comparing strings with
==in C instead ofstrcmp.
Each of these mistakes compiles without any warning, so the only way to catch them is to test with the key at the start, in the middle, at the end and missing.
Try it 3Search drill
Pick a mode. "Count" asks for mids and comparison counts on a fresh sorted array. "Rules" checks which search to use and why.
Summary
| Idea | Remember |
| Linear search | Check each item from the start until found or the end; works on any list. |
| Binary search | Sorted data only; check mid, discard half, repeat. |
| mid | (low + high) DIV 2, rounding down. |
| Not found | Linear: reach the end. Binary: low > high. Return -1. |
| Worst case | Linear: n comparisons. Binary: about log₂ n + 1. |
| Linked lists | Linear search only. |
Review questions
1. Describe how a linear search works.
Show answer
Starting at the first item, compare each item with the target in turn. Stop when the target is found (return its position) or when every item has been checked (report not found).
2. State the condition that must be true before a binary search can be used, and explain why.
Show answer
The list must be sorted. Binary search decides which half to discard by comparing with the middle item; this only works if all smaller items are on one side and all larger items on the other.
3. Write a C function that searches an integer array called num of n items for key, one item at a time, returning the index of key or -1.
Show answer
int linearSearch(int num[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (num[i] == key)
return i;
return -1;
}
4. Trace a binary search for 8 in [2, 5, 8, 12, 16, 23, 38]. Show low, high and mid.
Show answer
low=0, high=6, mid=3 (12 > 8) so high=2. low=0, high=2, mid=1 (5 < 8) so low=2. low=2, high=2, mid=2 (8) found at index 2. Three comparisons.
5. What is the maximum number of comparisons a binary search needs for 31 items? For a linear search?
Show answer
Binary: 5 (31 → 15 → 7 → 3 → 1). Linear: 31.
6. Why is binary search described as divide and conquer?
Show answer
Each step divides the remaining range in half and continues with only the half that can contain the key, so the problem shrinks quickly.
7. Give one situation where linear search is the better choice.
Show answer
When the data is unsorted and will only be searched once or twice, when the list is very small, or when the data is in a linked list.
8. A list contains 8, 9, 4, 5, 6, 9, 2. Can binary search be used on it? Explain.
Show answer
Not as it stands, because the list is not sorted. (Duplicates are not the problem.) It would first need to be sorted.
Homework
- Write a C program that reads 10 integers into an array, asks for a key, and uses linear search to print every index where the key appears.
- Trace binary search for 77 and for 40 on the 11-item array from Worked example 2. How many comparisons does each need?
- Write the binary search as a recursive function binarySearch(a, low, high, key).
- Copy the table in Part 2 and add a row for 1,000,000,000 items. How many comparisons does binary search need in the worst case?
- Explain, with an example, why binary search can give the wrong answer on unsorted data without crashing.
Mastery quiz: Linear and binary search
This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.
Mastery quiz: Searching in C: Linear Search and Binary Search
Your course badges: loading saved progress…
View badges
No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.
Saved in this browser on this device. Clearing browser data may remove your badges.
Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.
Exam tips
Specimen Unit 2 Paper 01 (2021), Items 8, 9 and 10. Item 8 gives an unordered array (with a repeated value) and some statements about binary search: the reason binary search cannot be used is that the list is not sorted, not that it has duplicates. Item 9 asks what is true of both searches: think carefully about sorted lists, worst cases and averages. Item 10 asks for the best description of binary search: divide and conquer.
Specimen Unit 2 Paper 02 (2021), Question 2(b). You write C code for a linear search on a named array, accepting a key and returning a result. Include the function header with the array, its size and the key; a loop over every index; the comparison; returning the index on a match; and returning -1 after the loop. Do not put "return -1" inside the loop, or the function will give up after the first item.
Trace tables. For binary search, always show low, high and mid on every row, and use whole-number division for mid. Examiners award marks for each correct row.
More worked answers are on the CS Solutions page.
Previous: Unit 2 • Module 1 • Lesson 06 – Singly Linked Lists: Diagrams, Algorithms and Array-Based Nodes in C. Next: Unit 2 • Module 1 • Lesson 08 – Selection Sort in C.
Syllabus link: CAPE Computer Science (CXC A19/U2/21), Data Structures (Unit 2, Module 1). Specific Objective 5: apply searching and sorting algorithms (linear search and binary search).
Video search terms
Search YouTube for: "linear search vs binary search", "binary search trace low high mid", "binary search in C".
Try it 4Quick quiz
Tap an answer. All eight questions are self-checks on this lesson.
Updates
2026/12/01
- First version of the lesson.
© 2026 islandclass.org
