Skip to content

Commit d63dbb1

Browse files
Merge pull request TheAlgorithms#122 from theycallmemac/master
added interpolationSearch.java
2 parents d1475f1 + 665c6f1 commit d63dbb1

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Searches/interpolationSearch.java

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

0 commit comments

Comments
 (0)