|
| 1 | +// C++ program to implement interpolation search |
| 2 | +#include<bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +// If x is present in arr[0..n-1], then returns |
| 6 | +// index of it, else returns -1. |
| 7 | +int interpolationSearch(int arr[], int n, int x) |
| 8 | +{ |
| 9 | + // Find indexes of two corners |
| 10 | + int lo = 0, hi = (n - 1); |
| 11 | + |
| 12 | + // Since array is sorted, an element present |
| 13 | + // in array must be in range defined by corner |
| 14 | + while (lo <= hi && x >= arr[lo] && x <= arr[hi]) |
| 15 | + { |
| 16 | + if (lo == hi) |
| 17 | + { |
| 18 | + if (arr[lo] == x) return lo; |
| 19 | + return -1; |
| 20 | + } |
| 21 | + // Probing the position with keeping |
| 22 | + // uniform distribution in mind. |
| 23 | + int pos = lo + (((double)(hi - lo) / |
| 24 | + (arr[hi] - arr[lo])) * (x - arr[lo])); |
| 25 | + |
| 26 | + // Condition of target found |
| 27 | + if (arr[pos] == x) |
| 28 | + return pos; |
| 29 | + |
| 30 | + // If x is larger, x is in upper part |
| 31 | + if (arr[pos] < x) |
| 32 | + lo = pos + 1; |
| 33 | + |
| 34 | + // If x is smaller, x is in the lower part |
| 35 | + else |
| 36 | + hi = pos - 1; |
| 37 | + } |
| 38 | + return -1; |
| 39 | +} |
| 40 | + |
| 41 | +// Driver Code |
| 42 | +int main() |
| 43 | +{ |
| 44 | + // Array of items on which search will |
| 45 | + // be conducted. |
| 46 | + int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, |
| 47 | + 22, 23, 24, 33, 35, 42, 47}; |
| 48 | + int n = sizeof(arr)/sizeof(arr[0]); |
| 49 | + |
| 50 | + int x = 18; // Element to be searched |
| 51 | + int index = interpolationSearch(arr, n, x); |
| 52 | + |
| 53 | + // If element was found |
| 54 | + if (index != -1) |
| 55 | + cout << "Element found at index " << index; |
| 56 | + else |
| 57 | + cout << "Element not found."; |
| 58 | + return 0; |
| 59 | +} |
| 60 | + |
| 61 | +// This code is contributed by Mukul Singh. |
0 commit comments