Given a sorted array of n integers and a target value, determine if the target exists in the array or not in logarithmic time. If the target exists in the array, return the index of it.

For example,

Input: A[] = [2, 3, 5, 7, 9]
target = 7
 
Output: Element found at index 3
 
 
Input: A[] = [1, 4, 5, 8, 9]
target = 2
 
Output: Element not found

Practice this problem

Exponential search is an algorithm used for searching sorted, unbounded/infinite arrays. The idea is to determine a range that the target value resides in and perform a binary search within that range. Assuming that the array is sorted in ascending order, it looks for the first exponent, k, where the value 2k is greater than the search key. Now 2k and 2k-1 becomes the upper bound and lower bound for the binary search algorithm, respectively.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

Element found at index 4

Java


Download  Run Code

Output:

Element found at index 4

Python


Download  Run Code

Output:

Element found at index 4

Performance

The exponential search takes O(log(i)) time, where i is the target’s position in the array when the target is in the array or position where the target should be if it isn’t in the array.

We can also use the exponential search to search in bounded arrays. It can even out-perform binary search when the target is near the beginning of the array. This is because the exponential search will run in O(log(i)) time, where i is the index of the element being searched for in the array, whereas binary search would run in O(log(n)) time, where n is the total number of elements in the array.

 
Exercise: Find where a strictly increasing function (f(x) > f(x-1) for all values of x) becomes positive for the first time. Consider f(x) = x2 + 2x - 400. It becomes positive for the first time for x = 20.

 
References: https://en.wikipedia.org/wiki/Exponential_search