问题描述:
N个有序整数数列已放在一堆数组中,利用二分查找法查找整数m在数组中的位置。若找到,则输出其下表值,反之则输出“Not be found!”
1.定义一个最低值位数low = 0,定义一个最高值位数high = N-1;
2.当low<=high时计算mid = (low + high)/ 2;
3.如果要找的值m < a[mid],high = mid -1
4.如果要找的值m >a[mid],low = mid +1
5.若找到则结束循环打印结果
#include<iostream>
#define N 10
using namespace std;
int main()
{
int i, a[N] = { -3,4,7,9,13,45,67,89,100,180 };
int low = 0, high = N - 1, mid, k = -1, m;
cout << "a数组中的数据如下:" << endl;
for (i = 0; i < N; i++)
cout << a[i]<<" ";
cout << endl;
cin >> m;
while (low <= high)
{
mid = (low + high) / 2;
if (m < a[mid])
high = mid - 1;
else
if (m > a[mid])
low = mid + 1;
else
{
k = mid;
break;
}
}
if (k >= 0)
cout << "m = " << m << " " << "index = " << k;
else cout << "Not be found!" << endl;
return 0;
}