
Sponsored
Sponsored
The iterative binary search approach involves using two pointers, 'left' and 'right'. We continue dividing the array into halves until we locate the target or determine where it should be inserted. The algorithm compares the target with the middle element and appropriately adjusts the 'left' or 'right' pointer based on this comparison.
Time Complexity: O(log n)
Space Complexity: O(1) since no extra space is used.
1#include <stdio.h>
2
3int searchInsert(int* nums, int numsSize, int target) {
4 int left = 0, right = numsSize - 1;
5 while (left <= right) {
6 int mid = left + (right - left) / 2;
7 if (nums[mid] == target) return mid;
8 else if (nums[mid] < target) left = mid + 1;
9 else right = mid - 1;
10 }
11 return left;
12}
13
14int main() {
15 int nums[] = {1, 3, 5, 6};
16 int target = 5;
17 int result = searchInsert(nums, 4, target);
18 printf("%d\n", result);
19 return 0;
20}
21This solution uses a binary search to find the target. If the target is found, it returns the index. If not, it returns the position where the target should be inserted to maintain sorted order.
In this approach, the binary search is implemented recursively. The function calls itself with updated bounds until the target is found or until it determines the correct insertion index. This approach makes use of stack space due to recursion but is logically intuitive.
Time Complexity: O(log n)
Space Complexity: O(log n) due to recursion stack.
1public
This Java solution recursively finds the index or insert point of the target via binary search.