| 1 | // Java program to implement interpolation |
| 2 | public class InterpolationSearch { |
| 3 | |
| 4 | public static void main(String[] args) { |
| 5 | Scanner sc = new Scanner(System.in); |
| 6 | int[] arr = {12, 23, 10, 34, 55, 4, 68, 3, 73}; |
| 7 | Arrays.sort(arr); |
| 8 | System.out.println("sorted array- " + Arrays.toString(arr)); |
| 9 | System.out.println("Enter value to search: "); |
| 10 | int searchElement = sc.nextInt(); |
| 11 | int index = interpolationSearch(arr, searchElement); |
| 12 | if(index != -1){ |
| 13 | System.out.println("Searched item " + arr[index] + " found at index "+index); |
| 14 | }else{ |
| 15 | System.out.println("Searched item " + searchElement + " not found in the array"); |
| 16 | } |
| 17 | sc.close(); |
| 18 | } |
| 19 | |
| 20 | private static int interpolationSearch(int[] arr, int searchElement){ |
| 21 | int start = 0; |
| 22 | int end = arr.length - 1; |
| 23 | int position; |
| 24 | while ((arr[end] != arr[start]) && (searchElement >= arr[start]) && (searchElement <= arr[end])) { |
| 25 | position = start + ((searchElement - arr[start]) * (end - start) / (arr[end] - arr[start])); |
| 26 | |
| 27 | if (arr[position] < searchElement) |
| 28 | start = position + 1; |
| 29 | else if (searchElement < arr[position]) |
| 30 | end = position - 1; |
| 31 | else |
| 32 | return position; |
| 33 | } |
| 34 | if (searchElement == arr[start]) |
| 35 | return start ; |
| 36 | else |
| 37 | return -1; |
| 38 | } |
| 39 | } |
nothing calls this directly
no outgoing calls
no test coverage detected