Sponsored
Sponsored
The iterative binary search approach involves using a loop to divide the array into halves repeatedly until the target is found or the search range is empty. This approach utilizes two pointers, 'low' and 'high', that represent the current search bounds.
Time Complexity: O(log n), as we divide the search space in half each time.
Space Complexity: O(1), only a constant amount of space is used.
1class Solution {
2 public int search(int[] nums, int target) {
3 int low = 0, high = nums.length - 1;
4 while (low <= high) {
5 int mid = low + (high - low) / 2;
6 if (nums[mid] == target) return mid;
7 else if (nums[mid] < target) low = mid + 1;
8 else high = mid - 1;
9 }
10 return -1;
11 }
12
13 public static void main(String[] args) {
14 Solution sol = new Solution();
15 int[] nums = {-1, 0, 3, 5, 9, 12};
16 int target = 9;
17 System.out.println(sol.search(nums, target));
18 }
19}
The Java implementation uses a while loop to perform binary search. The 'low' and 'high' pointers modify the search range based on comparisons.
The recursive binary search involves calling a function that repeatedly calls itself with updated bounds until the target is found or the bounds overlap. This approach provides a cleaner implementation at the cost of additional space used by the call stack.
Time Complexity: O(log n)
Space Complexity: O(log n) due to the stack space used by recursion.
1class
This Java solution recursively divides the search space in binary search, reducing the search scope in each recursive call.