![]() |
VOOZH | about |
The name of this searching algorithm may be misleading as it works in O(Log n) time. The name comes from the way it searches an element.
Given a sorted array, and an element x to be searched, find position of x in the array.
Input: arr[] = {10, 20, 40, 45, 55}
x = 45
Output: Element found at index 3
Input: arr[] = {10, 15, 25, 45, 55}
x = 15
Output: Element found at index 1
We have discussed, linear search, binary search for this problem.
Exponential search involves two steps:
How to find the range where element may be present?
The idea is to start with subarray size 1, compare its last element with x, then try size 2, then 4 and so on until last element of a subarray is not greater.
Once we find an index i (after repeated doubling of i), we know that the element must be present between i/2 and i (Why i/2? because we could not find a greater value in previous iteration)
We start with an index i equal to 1 and repeatedly double it until either i is greater than or equal to the length of the array or the value at index i is greater than or equal to the target value x. We then perform a binary search on the range [i/2, min(i, n-1)], where n is the length of the array. This range is guaranteed to contain the target value, if it is present in the array, because we know that the target value must be greater than or equal to the value at index i/2 and less than or equal to the value at index min(i, n-1). If we find the target value in the binary search, we return its index. Otherwise, we return -1 to indicate that the target value is not present in the array.
We mainly use recursive implementation of binary search once we find the range. We use iterative code to find the range.
Element is present at index 3
Here we use iterative implementation of binary search with the same approach.
Element is present at index 3