- Searching: linear vs binary
Check each item (, unsorted) or halve the range each step (, sorted).
A search algorithm finds the position of a target value in a list (or reports that it is absent).
Linear search checks each element in turn, from first to last:
FUNCTION LinearSearch(Target : INTEGER) RETURNS INTEGER
DECLARE i : INTEGER
FOR i ← 1 TO n
IF A[i] = Target THEN
RETURN i
ENDIF
NEXT i
RETURN 0 // not found
ENDFUNCTION
It works on unsorted data and, in the worst case, must compare every one of the items → time complexity .
Binary search is much faster but requires the data to be sorted. It repeatedly looks at the middle item and discards the half that cannot contain the target:
FUNCTION BinarySearch(Target : INTEGER) RETURNS INTEGER
DECLARE Low, High, Mid : INTEGER
Low ← 1
High ← n
WHILE Low <= High DO
Mid ← (Low + High) DIV 2
IF A[Mid] = Target THEN
RETURN Mid
ELSE
IF A[Mid] < Target THEN
Low ← Mid + 1
ELSE
High ← Mid - 1
ENDIF
ENDIF
ENDWHILE
RETURN 0 // not found
ENDFUNCTION
How performance varies with the number of items: for a linear search, doubling the data roughly doubles the worst-case work (). For a binary search, doubling the data adds just one extra comparison (). So for 1000 items, a linear search may need up to 1000 comparisons but a binary search needs only about 10.
- Linear search: check each item; unsorted data; .
- Binary search: check the middle, discard half; SORTED data; .
- Mid ← (Low + High) DIV 2; loop ends when Low > High (not found).
- Doubling n: +1 comparison for binary, ×2 work for linear.