#include<iostream> //二分查找binary search
using namespace std;
int main()
{
//定义数组
int array[] = { 1,2,13,19,20,22,41,55,68,72,81,98 };
int targetNumber; //要查找的数字,查找结果
int arrLength = sizeof(array) / sizeof(array[0]); //获得数组长度
printf("请输入在一下数组中要查找的数字\n");
//编写代码打印数组的内容
for(int i = 0; i < arrLength; i++)
printf("%d ",array[i]);
printf("\n");
scanf("%d",&targetNumber);
//查找
int low = 0,high = arrLength - 1,index = -1;
while(low <= high)
{
int mid = (high + low) / 2;
if(array[mid]==targetNumber)
{
index = mid;
break;
}
else if(array[mid] < targetNumber) low = mid + 1;
else high = mid - 1;
}
if(index == -1) printf("没有找到数字%d。",targetNumber);
else printf("找到了,%d是第%d个数字。",targetNumber,index);
return 0;
}
10-06
1301
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)