1
+
2
+ // Let's assume that the elements of the array are linearly distributed.
3
+
4
+ // General equation of line : y = m*x + c.
5
+ // y is the value in the array and x is its index.
6
+
7
+ // Now putting value of lo,hi and x in the equation
8
+ // arr[hi] = m*hi+c ----(1)
9
+ // arr[lo] = m*lo+c ----(2)
10
+ // x = m*pos + c ----(3)
11
+
12
+ // m = (arr[hi] - arr[lo] )/ (hi - lo)
13
+
14
+ // subtracting eqxn (2) from (3)
15
+ // x - arr[lo] = m * (pos - lo)
16
+ // lo + (x - arr[lo])/m = pos
17
+ // pos = lo + (x - arr[lo]) *(hi - lo)/(arr[hi] - arr[lo])
18
+
19
+ /* ************************************************/
20
+
21
+ // Algorithm
22
+ // The rest of the Interpolation algorithm is the same except for the above partition logic.
23
+ // Step1: In a loop, calculate the value of “pos” using the probe position formula.
24
+ // Step2: If it is a match, return the index of the item, and exit.
25
+ // Step3: If the item is less than arr[pos], calculate the probe position of the left sub-array. Otherwise, calculate the same in the right sub-array.
26
+ // Step4: Repeat until a match is found or the sub-array reduces to zero.
27
+
28
+ // Below is the implementation of the algorithm.
29
+
30
+ /* ************************************************/
31
+
32
+ #include < bits/stdc++.h>
33
+ using namespace std ;
34
+
35
+ int interpolationSearch (int arr[], int n, int x)
36
+ {
37
+ // Find indexes of two corners
38
+ int lo = 0 , hi = (n - 1 );
39
+
40
+ // Since array is sorted, an element present
41
+ // in array must be in range defined by corner
42
+ while (lo <= hi && x >= arr[lo] && x <= arr[hi])
43
+ {
44
+ if (lo == hi)
45
+ {
46
+ if (arr[lo] == x)
47
+ return lo;
48
+ return -1 ;
49
+ }
50
+ // Probing the position with keeping
51
+ // uniform distribution in mind.
52
+ int pos = lo + (((double )(hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo]));
53
+
54
+ // Condition of target found
55
+ if (arr[pos] == x)
56
+ return pos;
57
+
58
+ // If x is larger, x is in upper part
59
+ if (arr[pos] < x)
60
+ lo = pos + 1 ;
61
+
62
+ // If x is smaller, x is in the lower part
63
+ else
64
+ hi = pos - 1 ;
65
+ }
66
+ return -1 ;
67
+ }
68
+
69
+ // Driver Code
70
+ int main ()
71
+ {
72
+ // Array of items on which search will
73
+ // be conducted.
74
+ int arr[] = {10 , 12 , 13 , 16 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 33 , 35 , 42 , 47 };
75
+ int n = sizeof (arr) / sizeof (arr[0 ]);
76
+ int x = 18 ; // Element to be searched
77
+ int index = interpolationSearch (arr, n, x);
78
+
79
+ // If element was found
80
+ if (index != -1 )
81
+ cout << " Element found at index " << index;
82
+ else
83
+ cout << " Element not found." ;
84
+ return 0 ;
85
+ }
0 commit comments