二分法查找有序数组中某数的下标
int main(){
int arr[]={1,2,3,4,5,6,7,8,9,10,11};
int k=7;
int sz=sizeof(arr)/sizeof(arr);
int left=0;
int right=sz-1;
while(left<=right)
{
int mid=(left+right)/2;
if(arr>k)
{
right=mid-1;
}
else if (arr<k)
{
left=mid+1;
}
else
{
printf("找到了,k的下标是%d\n",mid);
break;
}
}
return 0;
}
文档来源:51CTO技术博客https://blog.51cto.com/u_15296521/3016905
页:
[1]