鶹Լ

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 “Found at position “&counter
                        else
                            set counter = counter + 1
                        end if
                    end while
                    if found = FALSE
                        output “Item 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.