DEV Community

loading...
Cover image for Linear Search Algorithm Using Python

Linear Search Algorithm Using Python

abhishek305 profile image Abhishek Ezhava ・2 min read

What is a Linear Search?

A linear search is the most basic kind of search that is performed. So how is it 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. You often do this in your daily life, say when you are looking through your shopping list to cross out an item you have picked up.

Benefits and Drawbacks
The benefit is that 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.

Coding a Linear Search
Let's first develop an algorithm for performing a linear search. We will then convert this into a Python script.

Let's start with a list of numbers, say 10 of them
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

Alt Text

Discussion

pic
Editor guide