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

31 lines
984 B
C++
Raw Normal View History

2019-10-02 17:03:24 +08:00
#include <iostream>
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
}
return -1;
2019-10-02 15:52:43 +08:00
}
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-27 04:40:09 +08:00
int index = InterpolationSearch(
A, 8, x); // passed array A inside the InterpolationSearch function
2019-10-02 17:03:24 +08:00
if (index != -1)
std::cout << "Number " << x << " is at " << index;
else
std::cout << "Number " << x << " not found";
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.