![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search Insert Position in C++
Suppose we have a sorted array arr and a target value, we have to find the index when the target is found. If that is not present, then return the index where it would be if it were inserted in order.
So, if the input is like [1,3,4,6,6], and target = 5, then the output will be 3, as we can insert 5 at index 3, so the array will be [1,3,4,5,6,6]
To solve this, we will follow these steps−
n := size of A
if n < 1, then −
return 0
low := 0, high := n - 1
while low <= high, do −
mid := low + (high - low) /2
if A[mid] is same as target, then −
return mid
otherwise when A[mid] > target, then −
high := mid - 1, pos := mid
otherwise
low := mid + 1, pos := mid + 1
return pos
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int searchInsert(vector<int>& A, int target) { int n = A.size(); if(n < 1) { return 0; } int low = 0; int high = n-1; int mid; int pos; while(low <= high) { mid = low + (high-low)/2; if(A[mid] == target) { return mid; } else if(A[mid] > target) { high = mid - 1; pos = mid; } else { low = mid + 1; pos = mid + 1; } } return pos; } }; main(){ Solution ob; vector<int&g; v = {1,3,4,6,6}; cout << (ob.searchInsert(v,5)); }
Input
{1,3,4,6,6},5
Output
3
Advertisements