Wednesday, May 10, 2017

Search Insert Position

Problem statement

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.

Link to GithubCode
Example
[1,3,5,6], 5  2
[1,3,5,6], 2  1
[1,3,5,6], 7  4
[1,3,5,6], 0  0


Solution

public class searchInsertPosition {
 
 public static int get(int [] arr,int insertValue)
 {
  int low=0;
  int high=arr.length-1;
  while(low<=high)
  {
   int mid=(low+high/2);
   //If mid is equal to insert value
   if(arr[mid]==insertValue)return mid;  
   //If mid is greater than the insertValue than we need traverse left to the mid 
    else if(arr[mid] >insertValue) high=mid-1;
   //If mid is less than the insertValue than we need to traverse right to the mid 
    else low=mid+1;
  }
  return low;
 }
 
}

No comments:

Post a Comment