问题描述:
N个有序整数数列已放在一维数组中,利用二分查找法查找整数m在数组中的位置。若找到,则输出其下标值;反之,则输出“Not be found! ”。
代码:
#include<iostream>
#define N 10
int main()
{
int k,i0=-1, a[N] = { 3,12,30,34,45,57,66,78,89,100 };
int mid = (N - 1) / 2;
int low = 0, high = N - 1;
std::cin >> k;
if (k > a[mid]) {
for (int i = mid + 1; i <= high; i++) {
if (a[i] == k) {
i0 = i;
std::cout << "下标为" << i0 << std::endl;
break;
}
}
}
else if (k < a[mid]) {
for (int i = mid-1 ; i >= low; i--) {
if (a[i] == k) {
i0 = i;
std::cout << "下标为" << i0 << std::endl;
break;
}
}
}
else if(k == a[mid]) {
i0 = mid;
std::cout << "下标为" << i0 << std::endl;
}
if (i0 ==-1) {
std::cout << "Not be found" << std::endl;
}
}