# Exponential Search

Data Structure AlgorithmsAlgorithmsSearching Algorithm

Exponential search is also known as doubling or galloping search. This mechanism is used to find the range where the search key may present. If L and U are the upper and lower bound of the list, then L and U both are the power of 2. For the last section, the U is the last position of the list. For that reason, it is known as exponential.

After finding the specific range, it uses the binary search technique to find the exact location of the search key.

## The complexity of Exponential Search Technique

• Time Complexity: O(1) for the best case. O(log2 i) for average or worst case. Where i is the location where search key is present.
• Space Complexity: O(1)

## Input and Output

Input:
A sorted list of data:
10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995
The search key 780
Output:
Item found at location: 16

## Algorithm

binarySearch(array, start, end, key)

Input: An sorted array, start and end location, and the search key

Output − location of the key (if found), otherwise wrong location.

Begin
if start <= end then
mid := start + (end - start) /2
if array[mid] = key then
return mid location
if array[mid] > key then
call binarySearch(array, mid+1, end, key)
else when array[mid] < key then
call binarySearch(array, start, mid-1, key)
else
return invalid location
End

exponentialSearch(array, start, end, key)

Input: An sorted array, start and end location, and the search key

Output: location of the key (if found), otherwise wrong location.

Begin
if (end – start) <= 0 then
return invalid location
i := 1
while i < (end - start) do
if array[i] < key then
i := i * 2 //increase i as power of 2
else
terminate the loop
done
call binarySearch(array, i/2, i, key)
End

## Example

#include<iostream>
using namespace std;

int binarySearch(int array[], int start, int end, int key) {
if(start <= end) {
int mid = (start + (end - start) /2); //mid location of the list
if(array[mid] == key)
return mid;
if(array[mid] > key)
return binarySearch(array, start, mid-1, key);
return binarySearch(array, mid+1, end, key);
}
return -1;
}

int exponentialSearch(int array[], int start, int end, int key){
if((end - start) <= 0)
return -1;
int i = 1; // as 2^0 = 1
while(i < (end - start)){
if(array[i] < key)
i *= 2; //i will increase as power of 2
else
break; //when array[i] corsses the key element
}
return binarySearch(array, i/2, i, key); //search item in the smaller range
}

int main() {
int n, searchKey, loc;
cout << "Enter number of items: ";
cin >> n;
int arr[n]; //create an array of size n
cout << "Enter items: " << endl;
for(int i = 0; i< n; i++) {
cin >> arr[i];
}
cout << "Enter search key to search in the list: ";
cin >> searchKey;
if((loc = exponentialSearch(arr, 0, n, searchKey)) >= 0)
cout << "Item found at location: " << loc << endl;
else
}
Enter number of items: 20
Item found at location: 16