-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathInterpolationSearch.java
More file actions
42 lines (35 loc) · 1.04 KB
/
InterpolationSearch.java
File metadata and controls
42 lines (35 loc) · 1.04 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
public class InterpolationSearch {
/**
* Performs Interpolation Search on a sorted array.
*
* @param arr Sorted array of integers
* @param key Element to search
* @return index of key if found, otherwise -1
*/
public static int interpolationSearch(int[] arr, int key) {
int low = 0;
int high = arr.length - 1;
while (low <= high && key >= arr[low] && key <= arr[high]) {
// Avoid division by zero
if (arr[high] == arr[low]) {
if (arr[low] == key) {
return low;
} else {
return -1;
}
}
// Estimate the position
int pos = low + ((key - arr[low]) * (high - low))
/ (arr[high] - arr[low]);
if (arr[pos] == key) {
return pos;
}
if (arr[pos] < key) {
low = pos + 1;
} else {
high = pos - 1;
}
}
return -1;
}
}