大象传媒

Sorting, searching and validation - EduqasLinear search

Sorting and searching are two of the most frequently needed tasks in program design. Common algorithms have evolved to take account of this need, such as linear search, binary search, bubble sort and merge sort.

Part of Computer ScienceUnderstanding Computer Science

Linear search

A is the simplest method of searching a set.

Searching data sets using the linear search algorithm

Starting at the beginning of the data set, each item of data is examined until a match is made. Once the item is found, the search ends.

A linear search works like this:

  1. Find out the length of the data set.
  2. Set counter to 0.
  3. Examine value held in the list at the counter position.
  4. Check to see if the value at that position matches the value searched for.
  5. If it matches, the value is found. End the search.
  6. If not, increment the counter by 1 and go back to step 3 until there are no more items to search.

Consider this list of unordered numbers:

Table with a list of unordered numbers

Suppose we were to search for the value 2. The search would start at position 0 and check the value held there, in this case 3.

3 does not match 2, so we move on to the next position.

The value at position 1 is 5.

5 does not match 2, so we move on to the next position.

The value at position 2 is 2 - a match. The search ends.

A linear search in might look like this:

find as integer
                    found as Boolean

                    counter as integer
                    list[8]
                    set find = 2
                    set found = FALSE
                    set counter = 0
                    while found = FALSE and counter < len(list)
                    聽聽聽聽if list[counter] = find
                    聽聽聽聽聽聽聽聽set found = TRUE
                    聽聽聽聽聽聽聽聽output 鈥淔ound at position 鈥&counter
                    聽聽聽聽else
                    聽聽聽聽聽聽聽聽set counter = counter + 1
                    聽聽聽聽end if
                    end while
                    if found = FALSE
                    聽聽聽聽output 鈥淚tem not found鈥
                    end if

Although a linear search is simple, it can be inefficient. Suppose the data set contained 100 items of data and the item searched for happens to be the last item in the set. All of the previous 99 items would have to be searched through first.

However, linear searches have the advantage that they will work on any data set whether it is ordered or unordered.