Binary Search in Python
This post demonstrates how to implement binary search in python.
Introduction
Binary Search is an algorithm for searching a specific value in an ordered collection. It can be used to search for either an index or an element in the collection. The algorithms divide the search space in two after every comparison.
Algorithm
Precondition: The collection must be sorted. If the collection is unordered, we need to sort it first before applying the binary search.
Steps
- Initialize
left
andright
to the index of left most and right most items in the given array to be searched. - Get the middle element between the
left
andright
index of the array. - compare
item
with the middle element. - If
item
matches with the middle element, return themiddle
index. - Else if
item
is greater than the middle element, thenitem
lies after the middle element on the right half of the array. - If
item
is smaller, theitem
lies before the middle element towards the left half of the array. - Repeat steps 1 to 5 until
left
has gone past theright
. - Return
False
or-1
(as error code) to indicate item not found.
The algorithm takes advantage of the ordering of the elements in the sorted array and ignores half of the element after each comparison.
Conclusion
The binary search algorithm has a time complexity of 𝑂(𝑙𝑜𝑔𝑛) and space complexity of 𝑂(1)