From f05e993bdd22ced1773f5a1599a3d6476fae0c6a Mon Sep 17 00:00:00 2001 From: Samruddhi Ghodake <72791227+samughodake@users.noreply.github.com> Date: Mon, 4 Oct 2021 18:06:01 +0530 Subject: [PATCH] chore(CPlusPlus): added search insert position (#508) Co-authored-by: Rahul Rajeev Pillai <66192267+Ashborn-SM@users.noreply.github.com> --- .../Arrays/search-insert-position.cpp | 69 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 11 +-- 2 files changed, 75 insertions(+), 5 deletions(-) create mode 100644 algorithms/CPlusPlus/Arrays/search-insert-position.cpp 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: "<