#include <stdio.h>
int bin_search(int arr[], int size, int key)
{
int left=0;
int right=size-1;
while (left<=right)
{
int mid=(left+right)/2;
if(arr[mid]>key)
right=mid-1;
else if(arr[mid]<key)
left = mid + 1;
else
{
return mid;//如果能找到,则返回mid下标
}
}
return -1;如果找不到,则返回-1
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9,10 };
int size=sizeof(arr)/sizeof(arr[0]);
int ret=bin_search(arr,size,3);//调用函数
if (ret==-1)
{
printf("not exist\n");
}
else
{
printf("%d\n",arr[ret]);
}
return 0;
}
本文出自 “阳光下的向日葵” 博客,请务必保留此出处http://10796797.blog.51cto.com/10786797/1706964
原文地址:http://10796797.blog.51cto.com/10786797/1706964