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.
1def binary_search(nums, target):
2 low, high = 0, len(nums) - 1
3 while low <= high:
4 mid = (low + high) // 2
5 if nums[mid] == target:
6 return mid
7 elif nums[mid] < target:
8 low = mid + 1
9 else:
10 high = mid - 1
11 return -1
12
13nums = [-1, 0, 3, 5, 9, 12]
14target = 9
15print(binary_search(nums, target))
This Python solution iteratively narrows down the search space using the 'low' and 'high' pointers to perform binary search.
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.