#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;
}
时间: 2024-10-06 01:39:38