|
| 1 | +// C++ program to find an element x in a |
| 2 | +// sorted array using Exponential search. |
| 3 | +#include <bits/stdc++.h> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +int binarySearch(int arr[], int, int, int); |
| 7 | + |
| 8 | +// Returns position of first occurrence of |
| 9 | +// x in array |
| 10 | +int exponentialSearch(int arr[], int n, int x) |
| 11 | +{ |
| 12 | + // If x is present at firt location itself |
| 13 | + if (arr[0] == x) |
| 14 | + return 0; |
| 15 | + |
| 16 | + // Find range for binary search by |
| 17 | + // repeated doubling |
| 18 | + int i = 1; |
| 19 | + while (i < n && arr[i] <= x) |
| 20 | + i = i*2; |
| 21 | + |
| 22 | + // Call binary search for the found range. |
| 23 | + return binarySearch(arr, i/2, min(i, n), x); |
| 24 | +} |
| 25 | + |
| 26 | +// A recursive binary search function. It returns |
| 27 | +// location of x in given array arr[l..r] is |
| 28 | +// present, otherwise -1 |
| 29 | +int binarySearch(int arr[], int l, int r, int x) |
| 30 | +{ |
| 31 | + if (r >= l) |
| 32 | + { |
| 33 | + int mid = l + (r - l)/2; |
| 34 | + |
| 35 | + // If the element is present at the middle |
| 36 | + // itself |
| 37 | + if (arr[mid] == x) |
| 38 | + return mid; |
| 39 | + |
| 40 | + // If element is smaller than mid, then it |
| 41 | + // can only be present n left subarray |
| 42 | + if (arr[mid] > x) |
| 43 | + return binarySearch(arr, l, mid-1, x); |
| 44 | + |
| 45 | + // Else the element can only be present |
| 46 | + // in right subarray |
| 47 | + return binarySearch(arr, mid+1, r, x); |
| 48 | + } |
| 49 | + |
| 50 | + // We reach here when element is not present |
| 51 | + // in array |
| 52 | + return -1; |
| 53 | +} |
| 54 | + |
| 55 | +// Driver code |
| 56 | +int main(void) |
| 57 | +{ |
| 58 | + int arr[] = {2, 3, 4, 10, 40}; |
| 59 | + int n = sizeof(arr)/ sizeof(arr[0]); |
| 60 | + int x = 10; |
| 61 | + int result = exponentialSearch(arr, n, x); |
| 62 | + (result == -1)? printf("Element is not present in array") |
| 63 | + : printf("Element is present at index %d", |
| 64 | + result); |
| 65 | + return 0; |
| 66 | +} |
0 commit comments