Search Insert Position

Given a sorted array 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.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

C++:
01 class Solution {
02 public:
03     int searchInsert(int A[], int n, int target) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         int p=0;
07         int q=n1;
08         while(p<=q)
09         {
10             int t=p+(qp)/2;
11             if(target==A[t])
12                 return t;
13             if(target<A[t])
14             {
15                 q=t1;
16             }
17             else
18             {
19                 p=t+1;
20             }
21         }
22         return p;
23     }
24 };
Advertisements
This entry was posted in Binary search. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s