TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
interpolation_search2.cpp
Go to the documentation of this file.
1
6#include <iostream>
7
15int InterpolationSearch(int A[], int n, int x) {
16 int low = 0;
17 int high = n - 1;
18 while (low <= high) {
19 int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low]));
20 if (x == A[mid])
21 return mid; // Found x, return (exit)
22 else if (x < A[mid])
23 high = mid - 1; // X lies before mid
24 else
25 low = mid + 1; // x lies after mid
26 }
27
28 return -1;
29}
30
32int main() {
33 int A[] = {2, 4, 5, 7, 13, 14, 15, 23};
34 int x = 17;
35
37 int index = InterpolationSearch(A, 8, x);
38 if (index < 0)
39 std::cout << "Number " << x << " not found" << std::endl;
40 else
41 std::cout << "Number " << x << " is at " << index << std::endl;
42}
43
44// randomly set x bcoz array was defined by us , therefore not reasonable for
45// asking input. We could have asked for input if array elements were inputed by
46// the user.
int InterpolationSearch(int A[], int n, int x)