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 <stdio.h>
2
3int binarySearch(int* nums, int numsSize, int target) {
4 int low = 0, high = numsSize - 1;
5 while (low <= high) {
6 int mid = low + (high - low) / 2;
7 if (nums[mid] == target) return mid;
8 else if (nums[mid] < target) low = mid + 1;
9 else high = mid - 1;
10 }
11 return -1;
12}
13
14int main() {
15 int nums[] = {-1, 0, 3, 5, 9, 12};
16 int target = 9;
17 int result = binarySearch(nums, 6, target);
18 printf("%d\n", result);
19 return 0;
20}
This C code implements an iterative binary search. It uses a loop to adjust the low and high pointers based on comparisons, eventually finding the target or concluding it is not present.
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#include
This C solution uses recursion to split the problem into smaller subproblems, updating 'low' and 'high' in each recursive call.