Given a sorted array and a target value, the target value found in the array, and returns its index, if not present in the target array, it will be returned in sequence inserted position.
Suppose the array without the repeating element
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 7
Output; 4
Examine a binary search
static int searchInsert ( int * nums, int numSize, int target)
{
int i = 0 ;
int j = numSize - 1 ;
int mid = 0 ;
if ( numSize == 0 ) return numSize;
while ( i<= j)
{
mid = ( i + j) >> 1 ;
if ( nums[ mid] == target)
{
return mid;
}
else if ( nums[ mid] > target)
{
j = mid - 1 ;
}
else
{
i = mid + 1 ;
}
}
return i;
}
int main ( )
{
int arr[ ] = { 1 , 2 , 4 , 5 , 9 } ;
int mid = searchInsert ( arr, sizeof ( arr) / sizeof ( arr[ 0 ] ) , 10 ) ;
printf ( "%d\n" , mid) ;
system ( "pause" ) ;
return 0 ;
}