File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments