91热爆

Linear search

A linear search is the simplest method of searching a set.

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 way to describe a linear search would be:

  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 pseudocode might look like this:

find = 2
found = Falselength = list.length
counter = 0
while found == False and counter < length
     if list[counter] == find then
          found = True
          print ('Found at position', counter)
     else:
          counter = counter + 1
     endif
endwhile
if found == False then
     print('Item not found')
endif

A linear search, although simple, can be quite 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.

Searching data sets using the linear search algorithm