|
| 1 | +/* |
| 2 | + Task : Exponential_Search.cpp |
| 3 | + Author : sumit-awasthi |
| 4 | + Language : C++ |
| 5 | + Explanation : |
| 6 | +*/ |
| 7 | +#include <bits/stdc++.h> |
| 8 | +#define all(x) begin(x), end(x) |
| 9 | +#define sz(x) (int)(x).size() |
| 10 | +#define MOD (LL)(1e9 + 7) |
| 11 | + |
| 12 | +#include<iostream> |
| 13 | + |
| 14 | +using namespace std; |
| 15 | +const int dir4[2][4] = {{1, -1, 0, 0}, {0, 0, 1, -1}}; |
| 16 | +const int dir8[2][8] = {{-1, -1, -1, 0, 1, 1, 1, 0}, {-1, 0, 1, 1, -1, 0, 1, -1}}; |
| 17 | + |
| 18 | +int binarySearch(int array[], int start, int end, int key) { |
| 19 | + if(start <= end) { |
| 20 | + int mid = (start + (end - start) /2); |
| 21 | + if(array[mid] == key) |
| 22 | + return mid; |
| 23 | + if(array[mid] > key) |
| 24 | + return binarySearch(array, start, mid-1, key); |
| 25 | + return binarySearch(array, mid+1, end, key); |
| 26 | + } |
| 27 | + return -1; |
| 28 | +} |
| 29 | + |
| 30 | +int exponentialSearch(int array[], int start, int end, int key){ |
| 31 | + if((end - start) <= 0) |
| 32 | + return -1; |
| 33 | + int i = 1; // as 2^0 = 1 |
| 34 | + while(i < (end - start)){ |
| 35 | + if(array[i] < key) |
| 36 | + i *= 2; |
| 37 | + else |
| 38 | + break; |
| 39 | + } |
| 40 | + return binarySearch(array, i/2, i, key); |
| 41 | +} |
| 42 | + |
| 43 | +int main() { |
| 44 | + int n, searchKey, loc; |
| 45 | + cout << "Enter number of items: "; |
| 46 | + cin >> n; |
| 47 | + int arr[n]; |
| 48 | + cout << "Enter items: " << endl; |
| 49 | + for(int i = 0; i< n; i++) { |
| 50 | + cin >> arr[i]; |
| 51 | + } |
| 52 | + cout << "Enter search key to search in the list: "; |
| 53 | + cin >> searchKey; |
| 54 | + if((loc = exponentialSearch(arr, 0, n, searchKey)) >= 0) |
| 55 | + cout << "Item found at Index= " << loc << endl; |
| 56 | + else |
| 57 | + cout << "Item is not found in the list." << endl; |
| 58 | + return 0; |
| 59 | +} |
0 commit comments