forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterpolationSearch.java
47 lines (41 loc) · 1.16 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
package com.rampatra.searching;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 9/1/15
* @time: 4:57 PM
*/
public class InterpolationSearch {
/**
* @param a
* @param k
* @return
*/
public static int search(int[] a, int k) {
int low = 0, high = a.length - 1, mid;
while (a[low] != a[high] && k >= a[low] && k <= a[high]) {
mid = low + (k - a[low]) * (high - low) / a[high] - a[low];
if (k < a[mid]) {
high = mid - 1;
} else if (k > a[mid]) {
low = mid + 1;
} else {
return mid;
}
}
if (k == a[low]) {
return low;
} else {
return -1;
}
}
public static void main(String[] args) {
System.out.println(search(new int[]{0, 2}, 2));
System.out.println(search(new int[]{0, 1}, 2));
System.out.println(search(new int[]{0, 1, 2, 3}, 2));
System.out.println(search(new int[]{0, 1, 2, 3}, 3));
System.out.println(search(new int[]{0, 2}, 0));
System.out.println(search(new int[]{0, 1, 2, 2, 2, 3, 3}, 2));
}
}