1. Linear search
A linear search sequentially checks each element of the array. It carries on until the matching element is found, or the end of the array is reached.
It starts at the beginning of the array. It does not require the elements to be sorted. Two stopping conditions are needed, so the loop tests both.
``` Count ← 1 Found ← FALSE WHILE Found = FALSE AND Count <= EndOfList IF Widgets[Count] = ToFind THEN Found ← TRUE ELSE Count ← Count + 1 ENDIF ENDWHILE ```
Examiner insight
Worked example 14 marks
Complete the pseudocode to find an item in a 1D array `Widgets` of type STRING, using a linear search.
``` TopOfList ← 1 EndOfList ← 50000 INPUT ToFind (1) ...... NotInList ← FALSE Count ← TopOfList WHILE (2) ...... AND ...... IF (3) ...... THEN Found ← TRUE ENDIF Count ← Count + 1 IF (4) ...... THEN NotInList ← TRUE ENDIF ENDWHILE ```
- 1
(1) `Found ← FALSE` [1]
- 2
(2) `Found = FALSE AND NotInList = FALSE`, or `Count <= EndOfList` as the second condition [1]
- 3
(3) `ToFind = Widgets[Count]` [1]
- 4
(4) `Found = FALSE AND Count > EndOfList` [1]