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.
1#include <iostream>
2#include <vector>
3
4int binarySearch(const std::vector<int>& nums, int target) {
5 int low = 0, high = nums.size() - 1;
6 while (low <= high) {
7 int mid = low + (high - low) / 2;
8 if (nums[mid] == target) return mid;
9 else if (nums[mid] < target) low = mid + 1;
10 else high = mid - 1;
11 }
12 return -1;
13}
14
15int main() {
16 std::vector<int> nums = {-1, 0, 3, 5, 9, 12};
17 int target = 9;
18 int result = binarySearch(nums, target);
19 std::cout << result << std::endl;
20 return 0;
21}
This C++ solution implements binary search iteratively, adjusting the search space with 'low' and 'high' pointers.
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.
1#
This C solution uses recursion to split the problem into smaller subproblems, updating 'low' and 'high' in each recursive call.