0984

Sorting and Searching Algorithms

Algorithm Design and Problem Solving · 4 question types

Exam Frequency Analysis

Past paper frequency (2018 to 2024)

This topic accounts for approximately 7% of your exam marks.

stable
Low
Stable7%

Bubble sort traces and binary search descriptions appear in nearly every paper. 4 to 6 marks.

A examines every item in a list one at a time, in order, until it either finds the target value or runs out of items.

The algorithm is the obvious approach: start at the beginning, check each value, stop when you find a match. It is sometimes called a sequential search.

Step-by-step algorithm

StepWhat it does
1Start at the first value in the list
2If this value is the target, stop and report found
3Otherwise, move to the next value
4Repeat steps 2-3
5If the end of the list is reached without finding the target, report not found

The algorithm works on any list, sorted or unsorted. This is its biggest advantage.

Linear search over the array NAMES looking for "BETH": each element from index 0 (JIM) onward is checked in turn — JIM, SALLY, ALEX, LIZ all fail — until BETH matches at index 4
Source: Linear Search by Save My Exams

Pseudocode

Found ← FALSE
FOR Index ← 1 TO LENGTH(Data)
   IF Data[Index] = Target
     THEN
        Found ← TRUE
        OUTPUT "Target found at position ", Index
   ENDIF
NEXT Index

IF Found = FALSE
  THEN
     OUTPUT "Target not found"
ENDIF

Advantages and disadvantages

AdvantagesDisadvantages
Works on any list, sorted or unsortedSlow on large lists: must check up to every item
Simple to writeIf the target is near the end (or not present), every item is checked
No setup cost (list does not need to be sorted first)

How long can a linear search take?

For a list of n items:

  • Best case: target is the first item; only 1 comparison needed.
  • Worst case: target is the last item, or not in the list; n comparisons needed.
  • Average case: roughly n/2 comparisons.

For 1 000 items, that is up to 1 000 comparisons. For 1 000 000 items, up to 1 000 000. Linear search does not scale well.