diff --git a/Search_algo/Interpolation_Search.cpp b/Search_algo/Interpolation_Search.cpp new file mode 100644 index 0000000..f213560 --- /dev/null +++ b/Search_algo/Interpolation_Search.cpp @@ -0,0 +1,69 @@ +/* +* C++ program to implement Interpolation Search. +* +* Interpolation Search is an improvement over Binary Search for instances +* where the values in a sorted array are uniformly distributed. +*/ + +#include +#include + +int interpolationSearch(const std::vector& arr, int x) { + int n = arr.size(); + if (n == 0) return -1; + + int lo = 0, hi = (n - 1); + + // Since array is sorted, an element present + // in array must be in range defined by corner + while (lo <= hi && x >= arr[lo] && x <= arr[hi]) { + if (lo == hi) { + if (arr[lo] == x) return lo; + return -1; + } + + // Probing the position with keeping + // uniform distribution in mind. + // pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[lo]) ] + int pos = lo + (((double)(hi - lo) / + (arr[hi] - arr[lo])) * (x - arr[lo])); + + // Condition of target found + if (arr[pos] == x) + return pos; + + // If x is larger, x is in upper part + if (arr[pos] < x) + lo = pos + 1; + // If x is smaller, x is in lower part + else + hi = pos - 1; + } + return -1; +} + +// Main function to test the algorithm +int main() { + std::vector arr = {10, 12, 13, 16, 18, 19, 20, 21, + 22, 23, 24, 33, 35, 42, 47}; + int x = 18; + + int index = interpolationSearch(arr, x); + + if (index != -1) { + std::cout << "Number " << x << " is at index " << index << std::endl; + } else { + std::cout << "Number " << x << " is not in the array" << std::endl; + } + + x = 30; + index = interpolationSearch(arr, x); + + if (index != -1) { + std::cout << "Number " << x << " is at index " << index << std::endl; + } else { + std::cout << "Number " << x << " is not in the array" << std::endl; + } + + return 0; +}