TheAlgorithms-C-Plus-Plus/search/interpolation_search2.cpp

47 lines
1.4 KiB
C++
Raw Normal View History

2020-05-29 08:35:12 +08:00
/**
* \file
* \brief [Interpolation
* search](https://en.wikipedia.org/wiki/Interpolation_search) algorithm
*/
2019-10-02 17:03:24 +08:00
#include <iostream>
2020-05-29 08:35:12 +08:00
/** function to search the value in an array using interpolation search
* \param [in] arr array to search in
* \param [in] value value to search for
* \param [in] len length of array
* \returns index where the value is found
* \returns -1 if not found
*/
2020-05-27 04:40:09 +08:00
int InterpolationSearch(int A[], int n, int x) {
2019-10-02 17:03:24 +08:00
int low = 0;
int high = n - 1;
2020-05-27 04:40:09 +08:00
while (low <= high) {
2019-10-02 17:03:24 +08:00
int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low]));
if (x == A[mid])
2020-05-27 04:40:09 +08:00
return mid; // Found x, return (exit)
2019-10-02 17:03:24 +08:00
else if (x < A[mid])
2020-05-27 04:40:09 +08:00
high = mid - 1; // X lies before mid
2019-10-02 17:03:24 +08:00
else
2020-05-27 04:40:09 +08:00
low = mid + 1; // x lies after mid
2019-10-02 17:03:24 +08:00
}
2020-05-29 08:35:12 +08:00
2019-10-02 17:03:24 +08:00
return -1;
2019-10-02 15:52:43 +08:00
}
2020-05-29 08:35:12 +08:00
/** main function */
2020-05-27 04:40:09 +08:00
int main() {
2019-10-02 17:03:24 +08:00
int A[] = {2, 4, 5, 7, 13, 14, 15, 23};
int x = 17;
2020-05-29 08:35:12 +08:00
///< passed array A inside the InterpolationSearch function
int index = InterpolationSearch(A, 8, x);
if (index < 0)
std::cout << "Number " << x << " not found" << std::endl;
2019-10-02 17:03:24 +08:00
else
2020-05-29 08:35:12 +08:00
std::cout << "Number " << x << " is at " << index << std::endl;
2019-10-02 15:52:43 +08:00
}
2020-05-27 04:40:09 +08:00
// randomly set x bcoz array was defined by us , therefore not reasonable for
// asking input. We could have asked for input if array elements were inputed by
// the user.