8000 Added algorithm in Java - InterpolationSearch. Ref #1 · RockLee444/Java-Algorithms@ab5d461 · GitHub
[go: up one dir, main page]

Skip to content

Commit ab5d461

Browse files
Vishal KukrejaVishal Kukreja
authored andcommitted
Added algorithm in Java - InterpolationSearch. Ref darpanjbora#1
1 parent 280509f commit ab5d461

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Searching/InterpolationSearch.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
//Java program to implement interpolation search
2+
public class InterpolationSearch {
3+
4+
// Array of items
5+
static int arr[] = new int[] { 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 27, 32, 35, 41, 45 };
6+
7+
// If x is present in arr[0..n-1], then it will return index of it, else -1.
8+
static int interpolationSearch(int x) {
9+
// Find indexes of two corners
10+
int lo = 0, hi = (arr.length - 1);
11+
12+
// Since array is sorted, an element present
13+
// in array must be in range defined by corner
14+
while (lo <= hi && x >= arr[lo] && x <= arr[hi]) {
15+
16+
if (lo == hi) {
17+
if (arr[lo] == x)
18+
return lo;
19+
return -1;
20+
}
21+
22+
// Probing the position with keeping
23+
// uniform distribution in mind.
24+
25+
int pos = lo + (((hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo]));
26+
27+
// Condition of target found
28+
if (arr[pos] == x)
29+
return pos;
30+
31+
// If x is larger, x is in upper part
32+
if (arr[pos] < x)
33+
lo = pos + 1;
34+
35+
// If x is smaller, x is in the lower part
36+
else
37+
hi = pos - 1;
38+
}
39+
return -1;
40+
}
41+
42+
// Driver method
43+
public static void main(String[] args) {
44+
int x = 18; // Element to be searched
45+
int index = interpolationSearch(x);
46+
47+
// If element was found
48+
if (index != -1)
49+
System.out.println("Element found at index " + index);
50+
else
51+
System.out.println("Element not found.");
52+
}
53+
}

0 commit comments

Comments
 (0)
0