chore(Java): added interpolation search (#522)

pull/524/head
Madhan Murugan 2021-10-06 18:28:10 +05:30 committed by GitHub
parent 6416651300
commit ea76010d17
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 51 additions and 0 deletions

View File

@ -44,6 +44,7 @@
2. [Jump Search](searching/jump-search.java) 2. [Jump Search](searching/jump-search.java)
3. [Linear Search](searching/linear-search.java) 3. [Linear Search](searching/linear-search.java)
4. [Allocate minimum number of pages](searching/allocate-min-pages.java) 4. [Allocate minimum number of pages](searching/allocate-min-pages.java)
5. [Interpolation Search](searching/interpolation-search.java)
## Sorting ## Sorting

View File

@ -0,0 +1,50 @@
// Java program to implement interpolation search with recursion
import java.util.*;
class GFG {
// If x is present in arr[0..n-1], then returns index of it, else returns -1.
public static int interpolationSearch(int arr[], int lo, int hi, int x)
{
int pos;
// Since array is sorted, an element present in array must be in rangedefined by corner
if (lo <= hi && x >= arr[lo] && x <= arr[hi]) {
// Probing the position with keeping uniform distribution in mind.
pos = lo + (((hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo]));
// Condition of target found
if (arr[pos] == x)
return pos;
// If x is larger, x is in right sub array
if (arr[pos] < x)
return interpolationSearch(arr, pos + 1, hi, x);
// If x is smaller, x is in left sub array
if (arr[pos] > x)
return interpolationSearch(arr, lo, pos - 1, x);
}
return -1;
}
// Driver Code
public static void main(String[] args)
{
// Array of items on which search will be conducted.
int arr[] = { 10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47 };
int n = arr.length;
// Element to be searched
int x = 18;
int index = interpolationSearch(arr, 0, n - 1, x);
// If element was found
if (index != -1)
System.out.println("Element found at index "+ index);
else
System.out.println("Element not found.");
}
}