-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpolation_search.cpp
52 lines (42 loc) · 1.08 KB
/
interpolation_search.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Author: Jakub Pawlina
// Algorithm: Interpolation Search
#include <bits/stdc++.h>
int interpolation_search(std::vector <int> data, int key)
{
int lower = 0, higher = data.size() - 1;
while (lower <= higher && data[lower] <= key && key <= data[higher])
{
if (lower == higher)
{
if (data[lower] == key) return lower;
return -1;
}
double fraction = (double) ((higher - lower) / (data[higher] - data[lower]));
int position = lower + (fraction * (key - data[lower]));
if (data[position] == key) return position;
if (data[position] < key) lower = position + 1;
if (data[position] > key) higher = position - 1;
}
return -1;
}
int32_t main()
{
int elements_number;
std::cin >> elements_number;
std::vector <int> data;
for (int i = 0; i < elements_number; ++i)
{
int tmp; std::cin >> tmp;
data.push_back(tmp);
}
int key_number;
std::cin >> key_number;
for (int i = 0; i < key_number; ++i)
{
int key; std::cin >> key;
int position = interpolation_search(data, key);
if (!~position) std::cout << "- ";
else std::cout << position + 1 << ' ';
}
return 0;
}