-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterpolation-Search.cpp
More file actions
71 lines (45 loc) · 1.52 KB
/
Interpolation-Search.cpp
File metadata and controls
71 lines (45 loc) · 1.52 KB
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
#include <iostream>
int Interpolation_Search(int arr[], int low, int high, int key);
int rec_Interpolation_Search(int arr[], int low, int high, int key);
int main(){
int arr[50], n, key;
std::cout<< "Enter the size of your array : " ;
std::cin >> n;
std::cout<< "Enter the elements of your array : " ;
for(int i=0; i<n; ++i)
std::cin >>arr[i];
std::cout<< "Enter the value to be search : ";
std::cin >> key;
int result = rec_Interpolation_Search(arr,0,n-1,key);
if(result == -1)
std::cout<< key <<" not exist!";
else
std::cout<< key << " found at index " << result;
return 0;
}
int Interpolation_Search(int arr[], int low, int high, int key){
while(low<=high && key >= arr[low] && key <= arr[high]){
int pos = low + (int)((high-low)/(arr[high]-arr[low])) * (key-arr[low]);
std::cin.get();
if(arr[pos] == key)
return pos;
else if(arr[pos] < key)
low = pos+1;
else
high = pos - 1;
}
return -1;
}
//Recusrive approach
int rec_Interpolation_Search(int arr[], int low, int high, int key){
if(low<=high && key >= arr[low] && key <= arr[high]){
int pos = low + (int)(high-low)/(arr[high]-arr[low]) * (key-arr[low]);
if(arr[pos] == key)
return pos;
else if(arr[pos] < key)
return rec_Interpolation_Search(arr, pos+1,high,key);
else
return rec_Interpolation_Search(arr,low,pos-1,key);
}
return -1;
}