Searching algorithms locate a target value within a data structure. AQA 7517 requires knowledge of linear search and binary search.
Examines each element one by one from the start until the target is found or the end is reached.
FUNCTION linearSearch(arr, target)
FOR i ← 0 TO len(arr) - 1
IF arr[i] = target THEN
RETURN i // Found at index i
END IF
END FOR
RETURN -1 // Not found
END FUNCTION
Repeatedly halves the search space by comparing the target with the middle element. Requires the array to be sorted.
FUNCTION binarySearch(arr, target)
left ← 0
right ← len(arr) - 1
WHILE left ≤ right
mid ← (left + right) DIV 2
IF arr[mid] = target THEN
RETURN mid
ELSE IF arr[mid] < target THEN
left ← mid + 1 // Target in right half
ELSE
right ← mid - 1 // Target in left half
END IF
END WHILE
RETURN -1 // Not found
END FUNCTION
// Array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] // Target: 23 // Indices: 0 1 2 3 4 5 6 7 8 9 Step 1: left=0, right=9, mid=4, arr[4]=16 < 23 → left=5 Step 2: left=5, right=9, mid=7, arr[7]=56 > 23 → right=6 Step 3: left=5, right=6, mid=5, arr[5]=23 = 23 → FOUND at index 5 ✓
| Feature | Linear Search | Binary Search |
|---|---|---|
| Time complexity (worst) | O(n) | O(log n) |
| Requires sorted data | No | Yes |
| Best for | Small/unsorted datasets | Large sorted datasets |
| Implementation | Simple | More complex |
| Comparisons (1000 items) | Up to 1000 | Up to 10 (log₂1000≈10) |
8 questions · instantly marked · AQA 7517 standard
| Term | Definition |
|---|
10 questions · 10 minutes