?在一个有序数组中查找具体的某个数字n,用二分法查找
代码示例:
#include <stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int se = (sizeof(arr)) / (sizeof(arr[0]));
int Num ;
printf("请输入1-10之间的任意整数:");
scanf("%d",&Num);
int right = se - 1;
int left = 0;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] < Num)
{
left = mid + 1;
}
else if (arr[mid] > Num)
{
right = mid - 1;
}
else//arr[mid] == Num
{
printf("找到了是第%d位\n",mid);
break;
}
}
if (left > right)
{
printf("找不到\n");
}
return 0;
运行结果:
请输入1-10之间的任意整数:7
找到了是第6位
请输入1-10之间的任意整数:20
找不到