Binary Search on Arrays
An Array to store the sorted integers and the key you are looking for are passed, and if that key is in an Array, it returns the Index of the key. If the key does not exist, -1 is returned.
Array with 47 keys and 20 elements
Solution
Runtime Complexity: O(logn) Memory Complexity: O(logn)
Binary Search is used to find the index of an element in a sorted array. If the element does not exist, it can be found as efficiently as it does. The algorithm divides the input array in half at each step. After every step, you can discard half of the array to see if the index you are looking for is found. Therefore, the solution can be calculated in O (logn) time.
code
The Iterative method using While loop instead of Recursive has the same speed efficiency, but Space Complexity can be O (1).