-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterpolation Search.cpp
More file actions
50 lines (48 loc) · 997 Bytes
/
Interpolation Search.cpp
File metadata and controls
50 lines (48 loc) · 997 Bytes
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
#include<bits/stdc++.h>
using namespace std;
Interpolation_Search(int a[],int k,int n)
{
int left = 0;
int right = n-1;
int middle;
int i = 0;
while(left <= right)
{
middle = left + ((int(right - left)/ (a[right] -a[left])) * (k - a[left]));
if(a[middle] == k)
{
return middle;
}
else if (a[middle]<k)
{
left = middle +1;
}
else
{
right = middle-1;
}
i++;
}
if(left > right)
{
return -1;
}
}
int main()
{
int n,a[10],k,i;
cout<<"Enter Element No :"<<endl;
cin>>n;
cout<<"Enter Element :"<<endl;
for(i = 0;i < n;i++)
{
cin>>a[i];
}
cout<<"Enter Key Number to Search"<<endl;
cin>>k;
int result = Interpolation_Search(a,k,n);
if(result == -1)
cout<<"Not Found";
else
cout<<"Found "<<endl<<"Position : "<<result+1;
}