What is a Linear Search?

A linear search is the most basic kind of search that is performed. A linear or sequential search, as the name suggests, is done when you inspect each item in a list one by one from one end to the other to find a match for what you are searching for.

Coding a Linear Search

Let’s first develop an algorithm for performing a linear search.

  • Let’s say, we have a list of 10 numbers.
  • First, we will ask for a number we think may be in the list. We will call this variable ”searchItem”
  • Also, we will set a flag variable called ”found” to false
  • Now loop thru the entire list from start to end
    • Compare the item at the current position in the list with ”searchItem”
    • If it matches then set ”found” to true and exit the loop, else move on to the next position
  • Otherwise, if we have searched the entire list, ”searchItem” was not found, so ”found” remains false
linear search diagram

Here’s the code in python using the algorithm above.

    numlist = [6, 3, 9, 2, 22, 34, 61, 74, 32, 92]
    print('List has the items: ', numlist)
    searchItem = int(input('Enter the Number, you want to search: '))
    found = False
    for i in range(len(numlist)):
        if numlist[i] == searchItem:
            found = True
            print(searchItem, ' was found at index ', i)
            break
    if found == False:
        print(searchItem, ' was not found in the list!')

Benefits and Drawbacks

It is a very simple search and easy to program. In the best-case scenario, the item you are searching for may be at the start of the list in which case you get it on the very first try.

Its drawback is that if your list is large, it may take a while to go through the list. In the worst-case scenario, the item you are searching for may not be in the list, or it may be at the opposite end of the list.

Please feel free to add-on or point out correction on my post in the comments section.

LEAVE A REPLY

Please enter your comment!
Please enter your name here