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 int searchInsert(int A[], int n, int target) {
02      if(target<=A[0])
03           return 0;
04      if(target>A[n1])
05           return n;
06      int i=0;
07      int j=n1;
08      while(i<j){
09          int mid=(i+j)/2;
10          if(A[mid]==target)
11              return mid;
12          if(A[mid]>target)
13              j=mid;
14          else
15              i=mid+1;
16     }
17     return j;
18 }
Advertisements
This entry was posted in Array and linked list, 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