Binary Search
Use on a sorted collection to discard half of the collection with each iteration. This narrows the collection down to the target value if one exists. If the loop runs to completion then the target value is not in the collection.
Time complexity: O(log n)
Space complexity: O(1) for iterative algorithm. O(log n) for recursive algorithm.
Iterative Algorithm
Note:
The
mid = (right + left) // 2
formula is fine for Python, where we don't need to worry about Integer overflow errors. In Java the formula should bemid = left + (right - left) / 2
. See Integer Overflow error in this article.
Recursive Algorithm
Resources
Last updated