Binary Search
The aim is to find the index of an element in a sorted array. The input must be an array sorted in ascending order.
We search the sorted array by repeatedly dividing the search interval in half. We begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, we narrow the interval to the lower half. Otherwise, we narrow it to the upper half. We repeatedly check until the value is found or the interval is empty.
Intuitive Example: Searching for the name of a person in a list of names sorted in alphabetical order.
Binary Search can be solved in both a recursive and iterative manner:
Python code for recursive Binary Search:
Python code for iterative Binary Search:
Time complexity: O(lg n)
Last updated