Python Data Structures Search Algorithms

Python Data Structures and Search Algorithms

Searching is a fundamental need when storing data in various data structures. The simplest approach is to iterate through each element in the data structure and match it with the value you are searching for. This is called a linear search. It is inefficient and rarely used, but creating a program for it can provide insights into how to implement some advanced search algorithms.

Linear Search

In this type of search, all items are searched sequentially, one by one. Each item is checked, and if a match is found, it is returned. Otherwise, the search continues until the end of the data structure.

Example

def linear_search(values, search_for):
search_at = 0
search_res = False
# Match the value with each data element
while search_at < len(values) and search_res is False:
if values[search_at] == search_for:
search_res = True
else:
search_at = search_at + 1
return search_res
l = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(l, 12))
print(linear_search(l, 91))

Output

When the above code is executed, it produces the following result –

Found 2 at index 0

Leave a Reply

Your email address will not be published. Required fields are marked *