
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.
1function searchInsert(nums, target) {
2 let left = 0;
3 let right = nums.length - 1;
4 while (left <= right) {
5 let mid = Math.floor(left + (right - left) / 2);
6 if (nums[mid] === target) return mid;
7 else if (nums[mid] < target) left = mid + 1;
8 else right = mid - 1;
9 }
10 return left;
11}
12
13let nums = [1, 3, 5, 6];
14let target = 5;
15console.log(searchInsert(nums, target));
16The JavaScript implementation uses binary search logic for determining the correct position of the target in the sorted array.
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.
1#include <vector>
using namespace std;
int binarySearch(vector<int>& nums, int left, int right, int target) {
if (left > right) return left;
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target)
return binarySearch(nums, mid+1, right, target);
else
return binarySearch(nums, left, mid-1, target);
}
int searchInsert(vector<int>& nums, int target) {
return binarySearch(nums, 0, nums.size() - 1, target);
}
int main() {
vector<int> nums = {1, 3, 5, 6};
int target = 5;
cout << searchInsert(nums, target) << endl;
return 0;
}
The C++ version implements a recursive form of binary search to decide on the position of the target.