From a34c308fdea300ac707a03560e0400e8a978d927 Mon Sep 17 00:00:00 2001 From: AbhiramSakha <143825001+AbhiramSakha@users.noreply.github.com> Date: Sat, 21 Mar 2026 08:41:46 +0530 Subject: [PATCH] fix: resolve formatting and build issues in IterativeBinarySearch --- .../searches/IterativeBinarySearch.java | 55 ++++++++++--------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java index 05fab0534267..cc0bfb16d26c 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java @@ -3,50 +3,53 @@ import com.thealgorithms.devutils.searches.SearchAlgorithm; /** - * Binary search is one of the most popular algorithms This class represents - * iterative version {@link BinarySearch} Iterative binary search is likely to - * have lower constant factors because it doesn't involve the overhead of - * manipulating the call stack. But in java the recursive version can be - * optimized by the compiler to this version. + * Binary search is one of the most popular algorithms. + * This class represents the iterative version of {@link BinarySearch}. * - *

- * Worst-case performance O(log n) Best-case performance O(1) Average - * performance O(log n) Worst-case space complexity O(1) + *

Iterative binary search avoids recursion overhead and uses constant space. * - * @author Gabriele La Greca : https://github.com/thegabriele97 - * @author Podshivalov Nikita (https://github.com/nikitap492) + *

Performance: + *

+ * + * @author Gabriele La Greca + * @author Podshivalov Nikita * @see SearchAlgorithm * @see BinarySearch */ public final class IterativeBinarySearch implements SearchAlgorithm { /** - * This method implements an iterative version of binary search algorithm + * Performs iterative binary search on a sorted array. * - * @param array a sorted array - * @param key the key to search in array - * @return the index of key in the array or -1 if not found + * @param array the sorted array + * @param key the element to search + * @param type of elements (must be Comparable) + * @return index of the key if found, otherwise -1 */ @Override public > int find(T[] array, T key) { - int l; - int r; - int k; - int cmp; + if (array == null || array.length == 0) { + return -1; + } - l = 0; - r = array.length - 1; + int left = 0; + int right = array.length - 1; - while (l <= r) { - k = (l + r) >>> 1; - cmp = key.compareTo(array[k]); + while (left <= right) { + int mid = (left + right) >>> 1; + int cmp = key.compareTo(array[mid]); if (cmp == 0) { - return k; + return mid; } else if (cmp < 0) { - r = --k; + right = mid - 1; } else { - l = ++k; + left = mid + 1; } }