From 8304f5e0e4f5efd293ba1ae583e10100bf4cf37a Mon Sep 17 00:00:00 2001 From: Lakshika Parihar <31981299+lakshika1064@users.noreply.github.com> Date: Fri, 10 Jan 2020 04:22:44 +0530 Subject: [PATCH] Interpolation search method (#287) * Interpolation search method * Delete interpolation_search.cpp * interpolation Search in C++ This algorithm follow the way we search a name in a phone book or a word in a dictionary * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Rename Search/interpolation_search.cpp to search/interpolation_search.cpp Co-authored-by: Christian Clauss --- search/interpolation_search.cpp | 36 +++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 search/interpolation_search.cpp diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp new file mode 100644 index 000000000..afa9e7c50 --- /dev/null +++ b/search/interpolation_search.cpp @@ -0,0 +1,36 @@ +#include + +// function to search the value in an array using interpolation search +int search(int arr[], int value, int len) { + int low = 0, high, mid; + high = len-1; + while (arr[low] <= value && arr[high] >= value) { + mid = (low + ((value-arr[low])*(high-low)) / (arr[high]-arr[low])); + if (arr[mid] > value) + high = mid-1; + else if (arr[mid] < value) + low = mid+1; + else + return mid; + } + if (arr[low] == value) + return low; + return 0; +} + +int main() { + int n, value, array[100], re; + std::cout << "Enter the size of array(less than 100) : "; + std::cin >> n; + std::cout << "array in ascending (increasing) order : " << std::endl; + for (int i=0; i < n; i++) + std::cin >> array[i]; + std::cout << "Enter the value you want to search : "; + std::cin >> value; + re = search(array, value, n); + if (re == 0) + std::cout << "Entered value is not in the array" << std::endl; + else + std::cout << "The value is at the position " << re << std::endl; + return 0; + }