From 3b0adbf469f98a06662d2735dad0a4ed5c061e10 Mon Sep 17 00:00:00 2001 From: Pranav Ghorpade Date: Thu, 29 Jan 2026 16:17:08 +0000 Subject: [PATCH 1/3] docs: Add comprehensive documentation to BinarySearch algorithm - Added detailed JavaDoc with @param, @return, @throws tags - Included step-by-step algorithm walkthrough example - Added inline comments explaining each code section - Documented time and space complexity analysis - Provided concrete usage examples with expected outputs - Explained edge cases and overflow prevention technique --- .../thealgorithms/searches/BinarySearch.java | 122 ++++++++++++++---- 1 file changed, 97 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index 0cac484d56b4..b98247daacd0 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -3,15 +3,39 @@ import com.thealgorithms.devutils.searches.SearchAlgorithm; /** - * Binary search is one of the most popular algorithms The algorithm finds the - * position of a target value within a sorted array - * IMPORTANT - * This algorithm works correctly only if the input array is sorted + * Binary Search Algorithm Implementation + * + * Binary search is one of the most efficient searching algorithms for finding a target + * element in a SORTED array. It works by repeatedly dividing the search space in half, + * eliminating half of the remaining elements in each step. + * + * IMPORTANT: This algorithm ONLY works correctly if the input array is sorted * in ascending order. - *

- * Worst-case performance O(log n) Best-case performance O(1) Average - * performance O(log n) Worst-case space complexity O(1) - * + * + * Algorithm Overview: + * 1. Start with the entire array (left = 0, right = array.length - 1) + * 2. Calculate the middle index + * 3. Compare the middle element with the target: + * - If middle element equals target: Found! Return the index + * - If middle element is less than target: Search the right half + * - If middle element is greater than target: Search the left half + * 4. Repeat until element is found or search space is exhausted + * + * Performance Analysis: + * - Best-case time complexity: O(1) - Element found at middle on first try + * - Average-case time complexity: O(log n) - Most common scenario + * - Worst-case time complexity: O(log n) - Element not found or at extreme end + * - Space complexity: O(1) - Only uses a constant amount of extra space + * + * Example Walkthrough: + * Array: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] + * Target: 7 + * + * Step 1: left=0, right=9, mid=4, array[4]=9 (9 > 7, search left half) + * Step 2: left=0, right=3, mid=1, array[1]=3 (3 < 7, search right half) + * Step 3: left=2, right=3, mid=2, array[2]=5 (5 < 7, search right half) + * Step 4: left=3, right=3, mid=3, array[3]=7 (Found! Return index 3) + * * @author Varun Upadhyay (https://github.com/varunu28) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm @@ -20,41 +44,89 @@ class BinarySearch implements SearchAlgorithm { /** - * @param array is an array where the element should be found - * @param key is an element which should be found - * @param is any comparable type - * @return index of the element + * Generic method to perform binary search on any comparable type. + * This is the main entry point for binary search operations. + * + * @param The type of elements in the array (must be Comparable) + * @param array The sorted array to search in (MUST be sorted in ascending order) + * @param key The element to search for + * @return The index of the key if found, -1 if not found + * + * @throws NullPointerException if array is null + * + * Example Usage: + *

+     * Integer[] numbers = {1, 3, 5, 7, 9, 11};
+     * int result = BinarySearch.find(numbers, 7);
+     * // result will be 3 (index of element 7)
+     * 
+     * int notFound = BinarySearch.find(numbers, 4);
+     * // notFound will be -1 (element 4 does not exist)
+     * 
*/ @Override public > int find(T[] array, T key) { + // Handle edge case: empty array if (array == null || array.length == 0) { return -1; } + + // Delegate to the core search implementation return search(array, key, 0, array.length - 1); } /** - * This method implements the Generic Binary Search - * - * @param array The array to make the binary search - * @param key The number you are looking for - * @param left The lower bound - * @param right The upper bound - * @return the location of the key + * Core recursive implementation of binary search algorithm. + * This method divides the problem into smaller subproblems recursively. + * + * How it works: + * 1. Calculate the middle index to avoid integer overflow + * 2. Check if middle element matches the target + * 3. If not, recursively search either left or right half + * 4. Base case: left > right means element not found + * + * @param The type of elements (must be Comparable) + * @param array The sorted array to search in + * @param key The element we're looking for + * @param left The leftmost index of current search range (inclusive) + * @param right The rightmost index of current search range (inclusive) + * @return The index where key is located, or -1 if not found + * + * Time Complexity: O(log n) because we halve the search space each time + * Space Complexity: O(log n) due to recursive call stack */ private > int search(T[] array, T key, int left, int right) { + // Base case: Search space is exhausted + // This happens when left pointer crosses right pointer if (right < left) { - return -1; // this means that the key not found + return -1; // Key not found in the array } - // find median - int median = (left + right) >>> 1; + + // Calculate middle index + // Using (left + right) / 2 could cause integer overflow for large arrays + // So we use: left + (right - left) / 2 which is mathematically equivalent + // but prevents overflow + int median = (left + right) >>> 1; // Unsigned right shift is faster division by 2 + + // Get the value at middle position for comparison int comp = key.compareTo(array[median]); + // Case 1: Found the target element at middle position if (comp == 0) { - return median; - } else if (comp < 0) { + return median; // Return the index where element was found + } + // Case 2: Target is smaller than middle element + // This means if target exists, it must be in the LEFT half + else if (comp < 0) { + // Recursively search the left half + // New search range: [left, median - 1] return search(array, key, left, median - 1); - } else { + } + // Case 3: Target is greater than middle element + // This means if target exists, it must be in the RIGHT half + else { + // Recursively search the right half + // New search range: [median + 1, right] return search(array, key, median + 1, right); } } From 8c851fffd16ee1b93b1ea074bebf1e93ff72364e Mon Sep 17 00:00:00 2001 From: Pranav Ghorpade Date: Thu, 29 Jan 2026 23:37:37 +0000 Subject: [PATCH 2/3] style: Apply proper Java formatting to BinarySearch - Fixed line length to meet style guidelines - Applied proper JavaDoc formatting - Corrected indentation and spacing - Ensured compliance with project formatting standards --- .../thealgorithms/searches/BinarySearch.java | 103 ++++++++---------- 1 file changed, 46 insertions(+), 57 deletions(-) diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index b98247daacd0..e28b35b81c74 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -4,38 +4,32 @@ /** * Binary Search Algorithm Implementation - * - * Binary search is one of the most efficient searching algorithms for finding a target - * element in a SORTED array. It works by repeatedly dividing the search space in half, - * eliminating half of the remaining elements in each step. - * - * IMPORTANT: This algorithm ONLY works correctly if the input array is sorted - * in ascending order. - * - * Algorithm Overview: - * 1. Start with the entire array (left = 0, right = array.length - 1) - * 2. Calculate the middle index - * 3. Compare the middle element with the target: - * - If middle element equals target: Found! Return the index - * - If middle element is less than target: Search the right half - * - If middle element is greater than target: Search the left half - * 4. Repeat until element is found or search space is exhausted - * - * Performance Analysis: - * - Best-case time complexity: O(1) - Element found at middle on first try - * - Average-case time complexity: O(log n) - Most common scenario - * - Worst-case time complexity: O(log n) - Element not found or at extreme end - * - Space complexity: O(1) - Only uses a constant amount of extra space - * - * Example Walkthrough: - * Array: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] - * Target: 7 - * - * Step 1: left=0, right=9, mid=4, array[4]=9 (9 > 7, search left half) - * Step 2: left=0, right=3, mid=1, array[1]=3 (3 < 7, search right half) - * Step 3: left=2, right=3, mid=2, array[2]=5 (5 < 7, search right half) - * Step 4: left=3, right=3, mid=3, array[3]=7 (Found! Return index 3) - * + * + *

Binary search is one of the most efficient searching algorithms for finding a target element + * in a SORTED array. It works by repeatedly dividing the search space in half, eliminating half of + * the remaining elements in each step. + * + *

IMPORTANT: This algorithm ONLY works correctly if the input array is sorted in ascending + * order. + * + *

Algorithm Overview: 1. Start with the entire array (left = 0, right = array.length - 1) 2. + * Calculate the middle index 3. Compare the middle element with the target: - If middle element + * equals target: Found! Return the index - If middle element is less than target: Search the right + * half - If middle element is greater than target: Search the left half 4. Repeat until element is + * found or search space is exhausted + * + *

Performance Analysis: - Best-case time complexity: O(1) - Element found at middle on first + * try - Average-case time complexity: O(log n) - Most common scenario - Worst-case time + * complexity: O(log n) - Element not found or at extreme end - Space complexity: O(1) - Only uses + * a constant amount of extra space + * + *

Example Walkthrough: Array: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] Target: 7 + * + *

Step 1: left=0, right=9, mid=4, array[4]=9 (9 > 7, search left half) Step 2: left=0, + * right=3, mid=1, array[1]=3 (3 < 7, search right half) Step 3: left=2, right=3, mid=2, + * array[2]=5 (5 < 7, search right half) Step 4: left=3, right=3, mid=3, array[3]=7 (Found! + * Return index 3) + * * @author Varun Upadhyay (https://github.com/varunu28) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm @@ -44,22 +38,20 @@ class BinarySearch implements SearchAlgorithm { /** - * Generic method to perform binary search on any comparable type. - * This is the main entry point for binary search operations. - * + * Generic method to perform binary search on any comparable type. This is the main entry point + * for binary search operations. + * * @param The type of elements in the array (must be Comparable) * @param array The sorted array to search in (MUST be sorted in ascending order) * @param key The element to search for * @return The index of the key if found, -1 if not found - * * @throws NullPointerException if array is null - * - * Example Usage: - *

+     *     

Example Usage: + *

      * Integer[] numbers = {1, 3, 5, 7, 9, 11};
      * int result = BinarySearch.find(numbers, 7);
      * // result will be 3 (index of element 7)
-     * 
+     *
      * int notFound = BinarySearch.find(numbers, 4);
      * // notFound will be -1 (element 4 does not exist)
      * 
@@ -70,30 +62,27 @@ public > int find(T[] array, T key) { if (array == null || array.length == 0) { return -1; } - + // Delegate to the core search implementation return search(array, key, 0, array.length - 1); } /** - * Core recursive implementation of binary search algorithm. - * This method divides the problem into smaller subproblems recursively. - * - * How it works: - * 1. Calculate the middle index to avoid integer overflow - * 2. Check if middle element matches the target - * 3. If not, recursively search either left or right half - * 4. Base case: left > right means element not found - * + * Core recursive implementation of binary search algorithm. This method divides the problem + * into smaller subproblems recursively. + * + *

How it works: 1. Calculate the middle index to avoid integer overflow 2. Check if middle + * element matches the target 3. If not, recursively search either left or right half 4. Base + * case: left > right means element not found + * * @param The type of elements (must be Comparable) * @param array The sorted array to search in * @param key The element we're looking for * @param left The leftmost index of current search range (inclusive) * @param right The rightmost index of current search range (inclusive) * @return The index where key is located, or -1 if not found - * - * Time Complexity: O(log n) because we halve the search space each time - * Space Complexity: O(log n) due to recursive call stack + *

Time Complexity: O(log n) because we halve the search space each time Space + * Complexity: O(log n) due to recursive call stack */ private > int search(T[] array, T key, int left, int right) { // Base case: Search space is exhausted @@ -107,21 +96,21 @@ private > int search(T[] array, T key, int left, int rig // So we use: left + (right - left) / 2 which is mathematically equivalent // but prevents overflow int median = (left + right) >>> 1; // Unsigned right shift is faster division by 2 - + // Get the value at middle position for comparison int comp = key.compareTo(array[median]); // Case 1: Found the target element at middle position if (comp == 0) { return median; // Return the index where element was found - } + } // Case 2: Target is smaller than middle element // This means if target exists, it must be in the LEFT half else if (comp < 0) { // Recursively search the left half // New search range: [left, median - 1] return search(array, key, left, median - 1); - } + } // Case 3: Target is greater than middle element // This means if target exists, it must be in the RIGHT half else { @@ -130,4 +119,4 @@ else if (comp < 0) { return search(array, key, median + 1, right); } } -} +} \ No newline at end of file From b145707023b01575dbc4f2828bf194d5cb3f7b85 Mon Sep 17 00:00:00 2001 From: Pranav Ghorpade Date: Thu, 29 Jan 2026 23:45:52 +0000 Subject: [PATCH 3/3] fix: correct Javadoc formatting and add missing newline at EOF - Fix Javadoc structure with proper tag ordering (description before @params) - Remove incorrect @throws tag (method returns -1, doesn't throw) - Format algorithm steps as proper HTML ordered list - Move complexity analysis before @param tags - Add missing newline at end of file - Fix example code to use instance method call --- .../thealgorithms/searches/BinarySearch.java | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index e28b35b81c74..7a5361b280ea 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -41,20 +41,20 @@ class BinarySearch implements SearchAlgorithm { * Generic method to perform binary search on any comparable type. This is the main entry point * for binary search operations. * - * @param The type of elements in the array (must be Comparable) - * @param array The sorted array to search in (MUST be sorted in ascending order) - * @param key The element to search for - * @return The index of the key if found, -1 if not found - * @throws NullPointerException if array is null - *

Example Usage: - *

+     * 

Example Usage: + *

      * Integer[] numbers = {1, 3, 5, 7, 9, 11};
-     * int result = BinarySearch.find(numbers, 7);
+     * int result = new BinarySearch().find(numbers, 7);
      * // result will be 3 (index of element 7)
      *
-     * int notFound = BinarySearch.find(numbers, 4);
+     * int notFound = new BinarySearch().find(numbers, 4);
      * // notFound will be -1 (element 4 does not exist)
      * 
+ * + * @param The type of elements in the array (must be Comparable) + * @param array The sorted array to search in (MUST be sorted in ascending order) + * @param key The element to search for + * @return The index of the key if found, -1 if not found or if array is null/empty */ @Override public > int find(T[] array, T key) { @@ -71,9 +71,16 @@ public > int find(T[] array, T key) { * Core recursive implementation of binary search algorithm. This method divides the problem * into smaller subproblems recursively. * - *

How it works: 1. Calculate the middle index to avoid integer overflow 2. Check if middle - * element matches the target 3. If not, recursively search either left or right half 4. Base - * case: left > right means element not found + *

How it works: + *

    + *
  1. Calculate the middle index to avoid integer overflow
  2. + *
  3. Check if middle element matches the target
  4. + *
  5. If not, recursively search either left or right half
  6. + *
  7. Base case: left > right means element not found
  8. + *
+ * + *

Time Complexity: O(log n) because we halve the search space each time. + * Space Complexity: O(log n) due to recursive call stack. * * @param The type of elements (must be Comparable) * @param array The sorted array to search in @@ -81,8 +88,6 @@ public > int find(T[] array, T key) { * @param left The leftmost index of current search range (inclusive) * @param right The rightmost index of current search range (inclusive) * @return The index where key is located, or -1 if not found - *

Time Complexity: O(log n) because we halve the search space each time Space - * Complexity: O(log n) due to recursive call stack */ private > int search(T[] array, T key, int left, int right) { // Base case: Search space is exhausted @@ -119,4 +124,4 @@ else if (comp < 0) { return search(array, key, median + 1, right); } } -} \ No newline at end of file +}