Given a sorted array, write a function to search first occurrence of a number in the array. If not found return -1.
Example::
{2,2,2,3,4,5,5,6,6,8,9}
search 6
Example::
{2,2,2,3,4,5,5,6,6,8,9}
search 6
should return 7.
给定一个排序的数组,找出数组中某个元素第一次出现的位置。如果没有找到返回-1.
int find_first_elem(int arr[],int low,int high,int elem)
{
if (low>high)
{
return -1;
}
int mid = low + (high-low)/2;
if (arr[mid] == elem)
{
int index = find_first_elem(arr,low,mid-1,elem);
return (index == -1?mid:index);//表示mid之前没有elem 返回mid 否则index
}
else
if (arr[mid]>elem)
{
find_first_elem(arr,low,mid-1,elem);
}
else
find_first_elem(arr,mid+1,high,elem);
}