From 30274042e3ab82cc31a9d6b6384fc1cf92667bb6 Mon Sep 17 00:00:00 2001 From: SankarshanMishra <124585946+SankarshanMishra@users.noreply.github.com> Date: Mon, 30 Oct 2023 01:26:20 +0530 Subject: [PATCH] Create InterpolationSearch #41 --- InterpolationSearch | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 InterpolationSearch diff --git a/InterpolationSearch b/InterpolationSearch new file mode 100644 index 0000000..6c81f60 --- /dev/null +++ b/InterpolationSearch @@ -0,0 +1,29 @@ +public class InterpolationSearch { + public static int interpolationSearch(int[] arr, int target) { + int left = 0; + int right = arr.length - 1; + + while (left <= right && target >= arr[left] && target <= arr[right]) { + int pos = left + ((target - arr[left]) * (right - left) / (arr[right] - arr[left])); + if (arr[pos] == target) { + return pos; + } else if (arr[pos] < target) { + left = pos + 1; + } else { + right = pos - 1; + } + } + return -1; + } + + public static void main(String[] args) { + int[] arr = {2, 5, 8, 12, 16, 23, 38, 42, 56, 72, 91}; + int target = 23; + int index = interpolationSearch(arr, target); + if (index != -1) { + System.out.println("Element found at index: " + index); + } else { + System.out.println("Element not found in the array."); + } + } +}