Implement Linear Search using Python
Technology and generation are growing up together, and the younger generation users are somewhat connected with tech and the internet all the time. Not to mention, today the whole world in this time of crisis is working over the internet. But to make these technologies, softwares, etc a software developer must have excellent problem-solving skills. In this world where the internet is the new fuel, one needs to be pretty sharp. And by sharp, for software developers, it means knowing how to automate real-world problems using computer programs. Data structures help a lot in this journey of logic building. So today we’re going to write a simple data structure program to Implement Linear Search using Python.
What is A Linear Search?
Linear search is the most basic searching for all algorithms in data structures. Also, it’s pretty easy to understand. But due to its slow searching speed, the Linear search algorithm is pretty rare to see in practical usage.
In a list/array to use Linear search one has to traverse the list/array at a time. Due to this reason, the time complexity of this algorithm is higher.
What’s The Approach?
- In an input array, we’ll start with the leftmost element index. We’ll traverse the array one by one comparing the number to be found (
x
) with the element present in the array.
- If
X
matches with the array element then we’ll print the index. Otherwise, we’llreturn -1.
Also Read: Multiply Integers without Multiplication Arithmetic Operator in Python
Python Program To Implement Linear Search
Input:
2, 3, 4, 10, 40
Output:
Element is present at index 3
# Python program for Linear search def search(arr, n, x): for i in range(0, n): if (arr[i] == x): return i return -1 # Driver Code arr = [2, 3, 4, 10, 40] x = 10 n = len(arr) # Function call result = search(arr, n, x) if(result == -1): print("Element is not present in array") else: print("Element is present at index", result)