#include <stdio.h>
int asd(int arr[], int a, int b)
{
int zuo = 0;
int you = b - 1;
while (zuo <= you)
{
int zhong = (zuo + you) / 2; //中间元素的下表的计算必须放在循环内,因为每一次二分查找 都会重新计算
//中间下表,如果放在循环外面就会陷入死循环
if (a > arr[zhong])
{
zuo = zhong + 1;
}
else if (a < arr[zhong])
{
you = zhong - 1;
}
else
return zhong;
}
return -1;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int a ;
int b = sizeof(arr) / sizeof(arr[0]); //暂时记住数组长度不能在函数中计算
int c;
printf("请输入一个数字:");
scanf("%d", &a);
c = asd(arr, a, b);
if (c == -1)
printf("该数不存在此数组中");
else
printf("找到了下标为%d", c);
return 0;
}