-
Notifications
You must be signed in to change notification settings - Fork 0
BinarySearch
R.Krishanthan edited this page Dec 16, 2025
·
1 revision
Implement a binary search algorithm that efficiently finds the position of a target value within a sorted array.
Binary search is a divide-and-conquer algorithm that repeatedly divides the search interval in half. It works only on sorted arrays.
- Time Complexity: O(log n) - much faster than linear search
-
Space Complexity:
- O(1) for iterative implementation
- O(log n) for recursive implementation (call stack)
- Requirement: Array must be sorted
- Best for: Large sorted datasets
- Compare the target with the middle element
- If target equals middle element, return the index
- If target is less than middle, search the left half
- If target is greater than middle, search the right half
- Repeat until target is found or the search space is empty
Implement the following methods in BinarySearch.java:
-
searchIterative(int[] arr, int target)- Iterative implementation -
searchRecursive(int[] arr, int target)- Recursive implementation -
searchRecursive(int[] arr, int target, int left, int right)- Helper method
- Empty array
- Single element array (found and not found)
- Target at the beginning
- Target at the end
- Target in the middle
- Target not in array
- Even and odd length arrays
- Use two pointers:
leftandright - Calculate middle as
left + (right - left) / 2to avoid overflow - Be careful with boundary conditions
- For recursion, think about the base case
- Integer overflow when calculating middle: use
left + (right - left) / 2instead of(left + right) / 2 - Off-by-one errors with array indices
- Infinite loops if not updating pointers correctly
- How would you find the first occurrence of a target in an array with duplicates?
- How would you find the last occurrence?
- Can you modify this to find the insertion position for a target not in the array?
- What's the difference in space complexity between iterative and recursive approaches?
- Lower bound (find first position where element >= target)
- Upper bound (find first position where element > target)
- Binary search on answer (for optimization problems)
- Linear Search
- Jump Search
- Interpolation Search
- Exponential Search