1. Understand the Goal: The user wants a Java implementation of the binary search algorithm.
-
Identify Key Concepts:
- Binary Search: An efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.
- Pre-condition: The array (or collection) must be sorted.
- Time Complexity: O(logn).
- Space Complexity: O(1) for iterative, O(logn) for recursive (stack space).
-
Determine the Approach:
- I should provide the Iterative approach (most common, efficient memory usage).
- I should also provide the Recursive approach (good for understanding the concept).
- I need a
main method to demonstrate how to use it.
- I should explain how it works.
- I should mention edge cases (element not found).
-
Drafting the Code (Iterative):
- Method signature:
public static int binarySearch(int[] array, int target)
- Variables:
low (0), high (length - 1).
- Loop condition:
while (low <= high)
- Mid calculation:
int mid = low + (high - low) / 2; (Use this instead of (low + high) / 2 to prevent integer overflow, though a simple example might not strictly need it, it's best practice).
- Comparison logic:
- If
array[mid] == target, return mid.
- If
array[mid] < target, low = mid + 1.
- If
array[mid] > target, high = mid - 1.
- Return -1 if not found.
-
Drafting the Code (Recursive):
- Method signature:
public static int binarySearchRecursive(int[] array, int target, int low, int high)
- Base case:
if (low > high) return -1.
- Mid calculation: same as above.
- Comparison logic:
- If match, return
mid.
- If less, recurse with
(array, target, mid + 1, high).
- If greater, recurse with
(array, target, low, mid - 1).
-
Structuring the Explanation:
- Introduction: Briefly define binary search and the sorting requirement.
- Iterative Implementation: Provide the code. This is usually the preferred one for interviews.
- Recursive Implementation: Provide the code as an alternative.
- Example Usage: A
main class showing test cases (found and not found).
- Key Concepts: Explain the time complexity (O(logn)) and the overflow-safe mid calculation.
-
Refining the Code (Self-Correction during drafting):
- Wait, should I use
java.util.Arrays? The prompt asks to implement it, not use the built-in library. However, mentioning that Arrays.binarySearch exists is a nice bonus tip.
- Variable naming:
left and right are also common, but low and high are very standard. I'll stick to low and high.
-
Final Code Assembly:
public class BinarySearch {
// Iterative approach
public static int search(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
// Prevent integer overflow compared to (left + right) / 2
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
// ... add recursive version and main ...
}
-
Final Polish: Add comments explaining the logic. Ensure the explanation covers why the array must be sorted.
-
Output Generation: (Proceed to generate the response based on these steps).
Here is a complete implementation of the Binary Search algorithm in Java.
I have included two approaches:
- Iterative (Recommended): Uses a
while loop. It is more memory efficient (O(1) space).
- Recursive: Uses method calls. It is elegant but uses stack memory (O(logn) space).
Java Implementation
public class BinarySearchExample {
// 1. Iterative Approach (Recommended)
public static int binarySearchIterative(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
// Calculate mid preventing integer overflow
int mid = left + (right - left) / 2;
// Check if target is present at mid
if (arr[mid] == target) {
return mid;
}
// If target is greater, ignore left half
if (arr[mid] < target) {
left = mid + 1;
}
// If target is smaller, ignore right half
else {
right = mid - 1;
}
}
// Target not found
return -1;
}
// 2. Recursive Approach
public static int binarySearchRecursive(int[] arr, int target, int left, int right) {
if (left <= right) {
int mid = left + (right - left) / 2;
// If the element is present at the middle
if (arr[mid] == target) {
return mid;
}
// If element is smaller than mid, then it can only be present in left subarray
if (arr[mid] > target) {
return binarySearchRecursive(arr, target, left, mid - 1);
}
// Else the element can only be present in right subarray
return binarySearchRecursive(arr, target, mid + 1, right);
}
// Target not found
return -1;
}
public static void main(String[] args) {
// NOTE: Binary search requires a SORTED array
int[] sortedArray = { 2, 5, 8, 12, 16, 23, 38, 56, 72, 91 };
int target = 23;
// Test Iterative
int resultIterative = binarySearchIterative(sortedArray, target);
if (resultIterative == -1)
System.out.println("Iterative: Element not found");
else
System.out.println("Iterative: Element found at index " + resultIterative);
// Test Recursive
int resultRecursive = binarySearchRecursive(sortedArray, target, 0, sortedArray.length - 1);
if (resultRecursive == -1)
System.out.println("Recursive: Element not found");
else
System.out.println("Recursive: Element found at index " + resultRecursive);
}
}
Key Concepts
- Pre-requisite: The array must be sorted for binary search to work. If the data is unsorted, the algorithm will fail.
- Midpoint Calculation:
- You will notice I used
int mid = left + (right - left) / 2;.
- While
(left + right) / 2 looks simpler, it can cause an Integer Overflow if left and right are very large numbers (sum exceeding 2,147,483,647). The formula used in the code is overflow-safe.
- Time Complexity: O(logn) — extremely fast. For an array of 1 million elements, it takes at most ~20 comparisons to find a number.
- Built-in Alternative: Java provides a built-in method if you don't need to write the logic yourself:
import java.util.Arrays;
int index = Arrays.binarySearch(sortedArray, target);