From 9791f1663cc501f5fe47531baa2e6a54eeead3fb Mon Sep 17 00:00:00 2001 From: Amal Bijoy Date: Sun, 5 Apr 2026 22:27:11 +0530 Subject: [PATCH] Guard interpolation search denominator for equal endpoints --- Searching-algorithms/Interpolationsearch.java | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/Searching-algorithms/Interpolationsearch.java b/Searching-algorithms/Interpolationsearch.java index ed7bea1..44b738f 100644 --- a/Searching-algorithms/Interpolationsearch.java +++ b/Searching-algorithms/Interpolationsearch.java @@ -20,15 +20,20 @@ public static void main(String[] args) { } else { System.out.println("Element " + key + " was NOT Found in the entered Array."); } - } - public static int interpolationSearch(int arr[], int lo, int hi, int x) { - int pos; - if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { - pos = lo + ((hi - lo) * (x - arr[lo])) / (arr[hi] - arr[lo]); - if (arr[pos] == x) - return pos; - if (arr[pos] < x) - return interpolationSearch(arr, pos + 1, hi, x); + } + public static int interpolationSearch(int arr[], int lo, int hi, int x) { + int pos; + if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { + if (arr[lo] == arr[hi]) { + if (arr[lo] == x) + return lo; + return -1; + } + pos = lo + ((hi - lo) * (x - arr[lo])) / (arr[hi] - arr[lo]); + if (arr[pos] == x) + return pos; + if (arr[pos] < x) + return interpolationSearch(arr, pos + 1, hi, x); if (arr[pos] > x) return interpolationSearch(arr, lo, pos - 1, x); }