Skip to content

Commit 67a6699

Browse files
author
Your Name
committed
Interpolation search in C++
1 parent 8657bb6 commit 67a6699

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
/**
5+
* Interpolation search function.
6+
*
7+
* @param v Sorted vector on which the search will be performed.
8+
* @param x Element to be searched.
9+
* @return Element index if found; -1 otherwise.
10+
*/
11+
int interpolationSearch(const std::vector<long int> &v, long int x) {
12+
int lo = 0; // first index
13+
int hi = v.size() - 1; // last index
14+
15+
while(lo <= hi && x >= v[lo] && x <= v[hi]) {
16+
if(lo == hi) {
17+
if(v[lo] == x) return lo;
18+
return -1;
19+
}
20+
21+
// standard algorithm formula
22+
// pos is a higher value when the searched element is closer to v[hi]
23+
// pos is a lower value when the searched element is closer to v[lo]
24+
int pos = lo + (((double)(hi - lo)/(v[hi] - v[lo])) * (x - v[lo]));
25+
26+
if(v[pos] == x) return pos; // found
27+
28+
if(v[pos] < x) lo = pos + 1; // x is in upper part
29+
else hi = pos - 1; // x is in lower part
30+
}
31+
32+
return -1; // not found
33+
}
34+
35+
/**
36+
* Driver code.
37+
*/
38+
int main() {
39+
// sorted vector on which the search will be performed; [0, 30]
40+
std::vector<long int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
41+
long int x = 7; // element to be searched
42+
int index = interpolationSearch(v, x);
43+
44+
if(index != -1) std::cout << "Element found at index " << index;
45+
else std::cout << "Element not found";
46+
std::cout << std::endl;
47+
48+
return 0;
49+
}

0 commit comments

Comments
 (0)