Unable to open this exercise
Common exam pitfall
Students often forget to increment the index pointer inside the search loop, causing an infinite loop.
Students often set Found <- TRUE before verifying that Array[Index] equals Target.
A Linear Search (also called a sequential search) is an algorithm that inspects every element of a one-dimensional array one by one in sequence, starting from the first position (Index = 1), until either the target element is located or the entire array has been examined.
1. How Linear Search Works
Target: 42
Array: [ 17, 8, 42, 95, 31 ]
▲ ▲ ▲
│ │ └─ Match found! Set Found <- TRUE, stop search.
│ └────── Check Index 2 (8 != 42) -> Next
└────────── Check Index 1 (17 != 42) -> Next
Operational Steps:
- Initialize Flag and Pointer:
Found <- FALSE(tracks whether the target item has been located).FoundIndex <- -1(records the index location where the target resides).Index <- 1(starting array index).
- Sequential Loop:
- Repeat while
Index <= MaxSizeANDFound = FALSE. - If
Array[Index] = Target, setFound <- TRUEandFoundIndex <- Index. - Always increment
Index <- Index + 1to advance to the next position.
- Post-Loop Verification:
- Check
IF Found = TRUE: output the index position. ELSE: output a notification that the item was not present in the dataset.
2. Efficiency & Characteristics
Characteristic | Linear Search |
|---|---|
Data Order Requirement | None: Operates effectively on completely unsorted data. |
Best-Case Efficiency | $1$ comparison (target is at index 1). |
Worst-Case Efficiency | $N$ comparisons (target is at the very last index or completely absent). |
Average Comparisons | $\approx N / 2$ comparisons. |
Suitability | Ideal for small lists or unsorted data where overhead of sorting would exceed search savings. |
AI Socratic Tutor
Need guidance? Ask a question or use the hint below.
AI Socratic Tutor is an All-Access Benefit
Unlock step-by-step Socratic hints, algorithm trace table walkthroughs, and error diagnostics for every Cambridge exercise.
You're chatting with an AI tutor, not a person. AI can make mistakes, so double-check its answers.
Exam-Style Question: Complete the Linear Search Control Logic
Complete the missing keywords and variable values in the Cambridge linear search template for an array of 50 integers:
Found <- [Space 1]
Index <- 1
WHILE (Index <= 50) AND (Found = FALSE) DO
IF Scores[Index] = Target THEN
Found <- [Space 2]
Location <- Index
ENDIF
Index <- Index + [Space 3]
ENDWHILE
Interactive exercises for Module 2 and beyond require an active plan.