Search Algorithms In Python
Searching is the technique of selecting specific data from a collection of data based on some condition. You are familiar with this concept if you have ever performed web searches to locate pages containing some words or phrases. Searching for data stored in different data structures is a very crucial part of application development. In this article, I will discuss two Search algorithms used in python:
1. Linear Search algorithm
2. Binary search algorithm
The Linear Search
This is the simplest solution to a sequential search problem. I will demonstrate this algorithm using the code below. This code searches for an element in a list. Imagine we have a list of numbers `(List = [1, 2, 3, 9, 7, 4])` and we are to search for a specific number:
Steps to follow:
- Start from the leftmost element of the list and one by one compare `key` with each number of the list.
- If `key` matches with an element, return `True`.
- else, return `False`
def search(list1, n):
i = 0
while i < len(list1):
if list1[i] == n:
return True
i = i+1
return False
list1 = [1, 2, 3, 9, 7, 4]
n = 5
if search(list1, n):
print("number found")
else:
print("number not found")