-
Notifications
You must be signed in to change notification settings - Fork 17
/
InterpolationSearch.java
48 lines (42 loc) · 1.35 KB
/
InterpolationSearch.java
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
package by.andd3dfx.search;
/**
* Implement interpolation search in a sorted array. Return element index or -1 if it doesn't exist
*
* @see <a href="https://youtu.be/kRTntkCB_a4">Video solution</a>
*/
public class InterpolationSearch {
public static int perform(int[] array, int target) {
int min = 0;
int max = array.length - 1;
int steps = 0;
try {
while (min <= max) {
steps++;
int mid = determineMid(array, target, min, max);
if (mid < min) {
mid = min;
}
if (mid > max) {
mid = max;
}
if (array[mid] == target) {
return mid;
}
if (array[mid] < target) {
min = mid + 1;
} else {
max = mid - 1;
}
}
return -1;
} finally {
System.out.println("target: " + target + ", total steps count: " + steps);
}
}
static int determineMid(int[] array, int target, int min, int max) {
if (array[max] == array[min]) {
return min;
}
return min + (max - min) * (target - array[min]) / (array[max] - array[min]);
}
}