🔒 Pro · Component 2 · 2.3.1 Algorithms
2.3.1b Linear and Binary Search
OCR H446 · A Level Computer Science · ~18 min read
Notes
Video
Slides
Worksheet
Quiz

Linear Search

A linear search (also called sequential search) checks every element in a list one by one from the start until either the target is found or the entire list has been examined. It works on unsorted and sorted lists.

Algorithm

function linearSearch(arr, target)
    for i ← 0 to len(arr) - 1
        if arr[i] = target then
            return i       // found at index i
        endif
    next i
    return -1              // not found
endfunction

Worked Example

Find 35 in: [12, 45, 7, 35, 89, 3]

StepIndex checkedarr[i]arr[i] = 35?
1012No
2145No
327No
4335Yes — return 3

Complexity

CaseComparisonsTime Complexity
Best1 (target at index 0)O(1)
Worstn (not found or last element)O(n)
Averagen/2O(n)

Binary Search

A binary search finds a target in a sorted list by repeatedly halving the search space. Start at the middle — if the target is smaller, discard the right half; if larger, discard the left half. Repeat until found or search space empty.

Prerequisite

Binary search REQUIRES the list to be SORTED in ascending (or descending) order. If the list is unsorted, binary search will give wrong results. If you need to search an unsorted list, either sort it first (O(n log n)) then binary search, or use linear search directly.

Algorithm (Iterative)

function binarySearch(arr, target)
    low ← 0
    high ← len(arr) - 1
    while low ≤ high
        mid ← (low + high) DIV 2
        if arr[mid] = target then
            return mid
        else if arr[mid] < target then
            low ← mid + 1    // discard left half
        else
            high ← mid - 1   // discard right half
        endif
    endwhile
    return -1    // not found
endfunction

Algorithm (Recursive)

function binarySearchRec(arr, target, low, high)
    if low > high then return -1   // base case: not found
    mid ← (low + high) DIV 2
    if arr[mid] = target then
        return mid
    else if arr[mid] < target then
        return binarySearchRec(arr, target, mid + 1, high)
    else
        return binarySearchRec(arr, target, low, mid - 1)
    endif
endfunction

Worked Example

Find 31 in: [3, 9, 12, 17, 25, 31, 44, 58, 67, 82] (10 elements, sorted)

Steplowhighmidarr[mid]Action
10942525 < 31, so low ← 5
25975858 > 31, so high ← 6
356531Found! Return 5

Only 3 comparisons to find 31 in a list of 10. A linear search would have taken up to 6 comparisons.

Complexity

CaseComparisonsTime Complexity
Best1 (target at mid on first check)O(1)
Worst⌊log₂n⌋ + 1O(log n)
Averagelog₂nO(log n)

Comparison: Linear vs Binary Search

FeatureLinear SearchBinary Search
Requires sorted list?NoYes
Best caseO(1)O(1)
Worst caseO(n)O(log n)
Average caseO(n)O(log n)
For 1,000,000 elementsUp to 1,000,000 checksUp to 20 checks
ImplementationSimpleMore complex
Use whenSmall/unsorted listsLarge sorted lists

Why O(log n) for Binary Search?

After each comparison, the search space is halved. Starting with n elements:

  • After 1 comparison: n/2 elements remain
  • After 2 comparisons: n/4 elements remain
  • After k comparisons: n/2ᵏ elements remain
  • Search ends when n/2ᵏ = 1, so 2ᵏ = n, so k = log₂(n)

For n = 1,000,000: log₂(1,000,000) ≈ 20 comparisons maximum. This is why binary search is dramatically faster than linear search for large datasets.

Trace Table for Binary Search

The exam often asks you to trace binary search. Key variables: low, high, mid, arr[mid], comparison result.

Find 17 in: [5, 9, 13, 17, 22, 30, 41] (7 elements)

Iterationlowhighmid = (low+high)÷2arr[mid]Result
106317Found! Return 3

Lucky — found on first check! This is the O(1) best case.

Exam tip: Binary search uses mid ← (low + high) DIV 2 (integer division). When asked to trace binary search, always show low, high, mid, arr[mid], and the action taken. State whether you update low or high.
Exam tip: Know the number of comparisons: binary search on n=1024 elements requires at most log₂(1024) = 10 comparisons. For n=16: log₂(16) = 4. For n=32: log₂(32) = 5. Doubling n only adds one extra comparison.
✓ Notes completed!
Video coming soon
Click to advance · Arrow keys also work
Click slide or press arrow keys to navigate

Worksheet — 2.3.1b Linear and Binary Search

8 questions · 24 marks · instantly marked

Q1Write a linear search algorithm in pseudocode that searches for a target value in an array and returns its index, or -1 if not found.[3 marks]
✓ Mark scheme
function linearSearch(arr, target)
  for i ← 0 to len(arr) - 1 [1]
    if arr[i] = target then [1]
      return i
    endif
  next i
  return -1 [1]
endfunction
Award marks for: loop through all elements [1], comparison with target [1], returning index if found and -1 if not found [1].
Q2Trace linear search for target=7 in the array [4, 1, 9, 7, 3]. Show all comparisons made.[3 marks]
✓ Mark scheme
i=0: arr[0]=4, 4≠7, continue [0.5]
i=1: arr[1]=1, 1≠7, continue [0.5]
i=2: arr[2]=9, 9≠7, continue [0.5]
i=3: arr[3]=7, 7=7, return 3 [1]
4 comparisons made [0.5]
Q3State the time complexity of linear search in the best, worst, and average cases. Explain the best case.[3 marks]
✓ Mark scheme
Best case: O(1) [0.5] — target is found at the first position checked (index 0), so only 1 comparison is needed regardless of list size [0.5]. Worst case: O(n) [0.5] — target is the last element or not in the list at all; must check all n elements [0.5]. Average case: O(n) [0.5] — on average, the target is found after checking n/2 elements; this simplifies to O(n) [0.5].
Q4Write a binary search algorithm in pseudocode (iterative version). State one precondition required for binary search to work correctly.[4 marks]
✓ Mark scheme
Precondition: the list must be sorted (ascending order) [1].
function binarySearch(arr, target)
  low ← 0; high ← len(arr) - 1 [0.5]
  while low ≤ high [0.5]
    mid ← (low + high) DIV 2 [0.5]
    if arr[mid] = target then return mid [0.5]
    else if arr[mid] < target then low ← mid + 1 [0.5]
    else high ← mid - 1 [0.5]
    endif
  endwhile
  return -1 [0.5]
endfunction [0.5]
Q5Trace binary search for target=31 in the sorted array [3, 9, 12, 17, 25, 31, 44, 58, 67, 82]. Show low, high, mid, arr[mid] at each step.[4 marks]
✓ Mark scheme
Step 1: low=0, high=9, mid=4, arr[4]=25. 25<31, so low←5 [1]
Step 2: low=5, high=9, mid=7, arr[7]=58. 58>31, so high←6 [1]
Step 3: low=5, high=6, mid=5, arr[5]=31. 31=31, return 5 [1]
3 comparisons made to find 31 [1]
Q6A sorted list contains 1,048,576 (2²⁰) elements. What is the maximum number of comparisons needed to find any element using binary search? Show your reasoning.[2 marks]
✓ Mark scheme
Binary search worst case: ⌊log₂(n)⌋ + 1 comparisons. For n = 2²⁰ = 1,048,576: log₂(2²⁰) = 20 [1]. Maximum comparisons = 20 (or 21 depending on exact implementation). Each comparison halves the search space: 2²⁰ → 2¹⁹ → ... → 2⁰ = 1 → empty. So 20 halvings [1].
Q7Explain why binary search cannot be applied directly to an unsorted list. What would happen if you tried?[2 marks]
✓ Mark scheme
Binary search relies on the sorted order to make correct decisions: if arr[mid] < target, the target MUST be in the right half (mid+1 to high) only if the list is sorted. In an unsorted list, this assumption is false — the target could be anywhere [1]. Attempting binary search on an unsorted list would discard halves that might contain the target, potentially returning -1 (not found) even when the target exists, or returning the wrong index [1].
Q8Compare linear and binary search. In what situations would you choose each? Refer to time complexity in your answer.[3 marks]
✓ Mark scheme
Choose linear search when: the list is unsorted and sorting would be expensive; the list is small (overhead of binary search not worth it); you need to find ALL occurrences, not just the first [1]. Linear search: O(n) worst case — checks up to all n elements. Choose binary search when: the list is already sorted; the list is large and frequent searches are needed — O(log n) worst case is dramatically faster [1]. Example: 1,000,000 elements — linear needs up to 1,000,000 comparisons; binary needs at most 20. However, if the list is unsorted, you must sort it first (O(n log n)), making a single search less efficient. Sort-then-binary-search is worth it only if multiple searches are performed [1].
Topic Quiz
1 of 15
You scored
out of 15
🎯

Mini Test — 2.3.1b Linear & Binary Search

  • 10 questions · 10 marks · 10 minutes
  • 5 MCQ + 5 short answer
Card 1 of 15
Click to reveal
🎉
Complete!
TermDefinition
🔒
Pro Content
Subscribe to access all 69 OCR H446 A Level lessons.
£7.99/month
or £59/year
Subscribe now →
← 2.3.1a Stacks, Queues & Complexity 2.3.1 Algorithms Next: 2.3.1c Sorting Algorithms →