Implementation (algorithm specification)Linear search

Algorithms are created to allow users to tell a computer how to solve a problem. Understanding how to construct five of the most common algorithms is a critical skill for budding software developers.

Part ofComputing ScienceSoftware design and development

Linear search

A linear search algorithm is used to search a populated array for a value specified by the user. The user needs to enter the value that they would like the program to look for within the array. Once the value has been found the algorithm will generally stop checking the remainder of the array.

It is necessary to use a Boolean variable to determine whether or not the item has been found. This variable will be set to false unless the desired value matches an item held within the array.

Example

In this example, the array is called ‘nation’ and holds 10 values held within positions 0 to 9 (unless the HLL indexes from 1).

A counter is used to allow the algorithm to iterate over each array item. In this example it is presumed that the array/list has already been populated.

Reference language

Line 1 SET item_found TO FALSE
Line 2 SET counter TO 0
Line 3 RECEIVE desired_item FROM (STRING) KEYBOARD
Line 4 REPEAT
Line 5 IF desired_item = nation[counter] THEN
Line 6 SET item_found TO TRUE
Line 7 SEND "The program found " & desired_item & " at position " & counter & “ of the nation array.” TO DISPLAY
Line 8 ELSE
Line 9 SET counter TO counter + 1
Line 10 END IF
Line 11 UNTIL counter = 10 OR item_found = TRUE
Line 12 IF item_found = FALSE THEN
Line 13 SEND “The program did not find a match for “ & desired_item & “ within the nation array.” TO DISPLAY
Line 14 END IF