Linear search
An example of a computer searching algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. is linear search. This is a simple algorithm used to find a value in a list of dataUnits of information. In computing there can be different data types, including integers, characters and Boolean. Data is often acted on by instructions.. The algorithm runs as follows:
- Identify a search term.
- Look at the first item in the list.
- Compare the item with the search term.
- Is the current item the same as the search term? If so, the item has been found. If not, move to the next item.
- Repeat from step two until the last item in the list has been reached.
- If the end of the list has been reached and the search term has not been found, then the search term is not in the list and the algorithm can stop.
Linear search example
This algorithm could be used to search the following list for the number 1:
3, 2, 4, 1, 5
The algorithm would produce:
3, 2, 4, 1, 5 (1 compared to 3 - not found)
3, 2, 4, 1, 5 (1 compared to 2 - not found)
3, 2, 4, 1, 5 (1 compared to 4 - not found)
3, 2, 4, 1, 5 (1 compared to 1- found)
Because the linear search algorithm simply moves up the list and checks each item, the data in the list does not need to be in order. However, as the list gets longer the algorithm takes longer to run, making it inefficient for large lists.
In pseudocode Also written as pseudo-code. A method of writing up a set of instructions for a computer program using plain English. This is a good way of planning a program before coding., this may look like:
find <-- 1
found <-- False
length <-- length(list)
counter <-- 0
WHILE found = False AND counter <= length
IF list[counter] = find THEN
found <-- True
OUTPUT 'Found at position', counter
ELSE
counter <-- counter + 1
ENDIF
ENDWHILE
IF found = False THEN
OUTPUT 'Item not found'
ENDIF