Chapter 3
Chapter 3
, which makes it much user-friendly language. In this tutorial, we will learn the linear search in
Python. Searching is a technique to find the particular element is present or not in the given list.
ADVERTISEMENT
ADVERTISEMENT
o Linear Search
o Binary Search
Both techniques are widely used to search an element in the given list.
It is the simplest searching algorithm because it searches the desired element in a sequential ma
ADVERTISEMENT
It compares each and every element with the value that we are searching for.
If both are matched, the element is found, and the algorithm returns the key's index position.
Step - 1: Start the search from the first element and Check key = 7 with each element of list x.
1. LinearSearch(list, key)
2. for each item in the list
3. if item == value
4. return its index position
5. return -1
Python Program
Let's understand the following Python implementation of the linear search algorithm.
Program
Output:
which takes three arguments - list1, length of the list, and number to search.
We defined for loop and iterate each element and compare to the key value.
If element is found, return the index else return -1 which means element is not present in the list.
Linear search algorithm is suitable for smaller list (<100) because it check
every element to get the desired number. Suppose there are 10,000 element
list and desired element is available at the last position, this will consume much time by compari
else:
# Element is not present in the array
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output
Element is present at index 3
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output
Element is present at index 3
import bisect
# Test array
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binary_search_bisect(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output
Element is present at index 3