diff --git a/algorithms/CPlusPlus/Arrays/search-insert-position.cpp b/algorithms/CPlusPlus/Arrays/search-insert-position.cpp new file mode 100644 index 00000000..7127f475 --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/search-insert-position.cpp @@ -0,0 +1,69 @@ +/* +Description: Given a sorted array of distinct integers and a target value, +return the index if the target is found. If not, return the index where it +would be if it were inserted in order. + +Approach: Using Binary search to solve in least time complexity. + +Time Complexity: O(log n) +*/ + +#include +#include +using namespace std; + +//function +int searchInsert(vector& nums, int target) { + //starting index + int start=0; + //ending index + int end=nums.size()-1; + while(start<=end){ + //calculating mid element + int mid = start + (end-start)/2; + //if target found, return the index + if(nums[mid]==target){ + return mid; + } + if(nums[mid]>target){ + end=mid-1; + } + else{ + start=mid+1; + } + } + //returning end+1 so that we can get the index where the target element can be inserted + return end+1; + +} + +//main starts +int main() { + cout << "Enter number of elements in the array\n"; + int n; + cin>>n; + cout<<"Enter the array elements\n"; + vector nums(n); + for(int i=0;i>nums[i]; + } + cout<<"Enter the target element\n"; + int target; + cin>>target; + cout<<"The target element can be inserted at: "<