From 2535572a874e3a42eb9632432e4d816322483916 Mon Sep 17 00:00:00 2001 From: Tanishq Verma Date: Thu, 1 Apr 2021 14:08:51 +0530 Subject: [PATCH 1/2] Adding interpolation search algo --- searching/c-or-cpp/interpolation-search.cpp | 59 +++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 searching/c-or-cpp/interpolation-search.cpp diff --git a/searching/c-or-cpp/interpolation-search.cpp b/searching/c-or-cpp/interpolation-search.cpp new file mode 100644 index 00000000..9c3f9595 --- /dev/null +++ b/searching/c-or-cpp/interpolation-search.cpp @@ -0,0 +1,59 @@ +// C++ program to implement interpolation search +#include +using namespace std; + +// If x is present in arr[0..n-1], then returns +// index of it, else returns -1. +int interpolationSearch(int arr[], int n, int x) +{ + // Find indexes of two corners + 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. + 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 the lower part + else + hi = pos - 1; + } + return -1; +} + +// Driver Code +int main() +{ + // Array of items on which search will + // be conducted. + int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, + 22, 23, 24, 33, 35, 42, 47}; + int n = sizeof(arr)/sizeof(arr[0]); + + int x = 18; // Element to be searched + int index = interpolationSearch(arr, n, x); + + // If element was found + if (index != -1) + cout << "Element found at index " << index; + else + cout << "Element not found."; + return 0; +} \ No newline at end of file From 1860e5b25c2593de26ec0ffae961e69a872af94f Mon Sep 17 00:00:00 2001 From: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> Date: Fri, 2 Apr 2021 14:04:31 +0530 Subject: [PATCH 2/2] update searching index readme add interpolation search under c-or-cpp --- searching/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/searching/README.md b/searching/README.md index 8ce44d1a..271062a7 100644 --- a/searching/README.md +++ b/searching/README.md @@ -5,6 +5,7 @@ 1. [Linear Search](c-or-cpp/linear-search.cpp) 2. [Binary Search](c-or-cpp/binary-search.cpp) 3. [Jump Search](c-or-cpp/jump-search.cpp) +4. [Interpolation Search](c-or-cpp/interpolation-search.cpp) ### Python