forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpolation_Search.cpp
76 lines (62 loc) · 1.62 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
using namespace std;
int interpolation (int arr[100], int n, int val)
{
//Starting and ending index of the array
int high, low;
// Rise is the difference between high index and low index
// Run is the difference between value at high index and low index
int rise, run;
high = n - 1;
low = 0;
while( low <= high && val >= arr[low] && val <= arr[high])
{
rise = high - low;
run = arr[high] - arr[low];
if (high == low)
return 0;
int x, pos;
x = val - arr[low];
//Probing the position with keeping
// uniform distribution in mind.
if (run != 0)
pos = low + (x * rise) / run ;
else
pos = low + (x * rise);
if (arr[pos] == val)
return pos;
// If x is smaller, x is in the lower part
else if (val < arr[pos])
high = pos - 1;
//If x is larger, x is in upper part
else
low = pos + 1;
}
return -1;
}
int main()
{
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the sorted array: ";
for(int i = 0; i < n; i++)
cin >> arr[i];
int val;
cout << "Enter the value to be searched: ";
cin >> val;
int index;
index = interpolation(arr, n, val);
cout << "The element is present at index: " << index;
return 0;
}
/*Enter the number of elements: 6
Enter the sorted array: 2
4
6
8
10
12
Enter the value to be searched: 8
The element is present at index: 3*/