给定一个有序序列,查找与key相等的值,如果没有则返回-1(注意这里不要返回0,会和数组下标重复)
#include <stdio.h>
int binary_search(int a[],int left,int right,int key)
{
while(left <= right)
{
int mid = (left + right) /2;
if(a[mid] == key)
return mid;
else if(a[mid] < key)
{
left = mid + 1;
}
else
{
right = mid -1;
}
}
return -1;
}
int main()
{
int a[] = {1,2,3,4,5,6,7,8};
int index;
int right = sizeof(a)/sizeof(int);
index = binary_search(a,0,right-1,3);
printf("%d",index);
return 0;
}
网友评论