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.
1function binarySearch(nums, target) {
2 let low = 0, high = nums.length - 1;
3 while (low <= high) {
4 let mid = Math.floor((low + high) / 2);
5 if (nums[mid] === target) return mid;
6 else if (nums[mid] < target) low = mid + 1;
7 else high = mid - 1;
8 }
9 return -1;
10}
11
12const nums = [-1, 0, 3, 5, 9, 12];
13const target = 9;
14console.log(binarySearch(nums, target));
This JavaScript code performs binary search iteratively by using a loop to adjust the searching bounds 'low' and 'high'.
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.
1def
This Python implementation of recursive binary search updates 'low' and 'high' recursively, ending when the target is detected or ruled out.