
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- 2-3 Trees (Search and Insert) in C/C++?
- Insert into a Binary Search Tree in C++
- Binary Search Tree insert with Parent Pointer in C++
- Insert an element at second position in a C# List
- How to insert an item in a list at a given position in C#?
- Insert a specified element in a specified position in JavaScript?
- Insert a character at nth position in string in JavaScript
- Sort search results based on substring position in MySQL
- C program to insert a node at any position using double linked list
- Search for a character from a given position in Java
- Insert the specified element at the specified position in Java CopyOnWriteArrayList
- Insert() Method in C#
- Insert Interval in C++
- Insert a specified HTML text into a specified position in the JavaScript document?
- How to insert an object in a list at a given position in Python?

Advertisements