Skip to content

Commit b3d9dac

Browse files
author
Bhrigu Kansra
authored
Merge pull request #33 from Aks1307/patch-4
InterpolationSearch.cpp
2 parents e41c1d7 + 40c0931 commit b3d9dac

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

searching/InterpolationSearch.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// C program to implement interpolation search
2+
#include<stdio.h>
3+
4+
// If x is present in arr[0..n-1], then returns
5+
// index of it, else returns -1.
6+
int interpolationSearch(int arr[], int n, int x)
7+
{
8+
// Find indexes of two corners
9+
int lo = 0, hi = (n - 1);
10+
11+
// Since array is sorted, an element present
12+
// in array must be in range defined by corner
13+
while (lo <= hi && x >= arr[lo] && x <= arr[hi])
14+
{
15+
// Probing the position with keeping
16+
// uniform distribution in mind.
17+
int pos = lo + (((double)(hi-lo) /
18+
(arr[hi]-arr[lo]))*(x - arr[lo]));
19+
20+
// Condition of target found
21+
if (arr[pos] == x)
22+
return pos;
23+
24+
// If x is larger, x is in upper part
25+
if (arr[pos] < x)
26+
lo = pos + 1;
27+
28+
// If x is smaller, x is in the lower part
29+
else
30+
hi = pos - 1;
31+
}
32+
return -1;
33+
}

0 commit comments

Comments
 (0)