Searching and sorting algorithms - AQALinear search

Sorting and searching are two of the most frequently needed algorithms in program design. These algorithms have evolved to take account of this need.

Part ofComputer ScienceComputational thinking and problem solving

Linear search

A linear search is an example of a simple computer searching that is used to find a value in a list of .

Searching data sets using the linear search algorithm

The algorithm runs as follows:

  1. Identify a search term.
  2. Look at the first item in the list.
  3. Compare the item with the search term.
  4. Is the current item the same as the search term? If so, the item has been found. If not, move to the next item.
  5. Repeat from step two until the last item in the list has been reached.
  6. 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 , 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