二分法查找
作者:互联网
#include<iostream>
using namespace std;
int Search(int a[], int n, int key);
int main() {
int a[] = {3,5,6,9,12,15,19,30,45,50,55};
int k, x;
char again = 'n';
do {
cout << "你要找的数?";
cin >> x;
k = Search(a, sizeof(a) / sizeof(a[0]), x);
if (k >= 0)
cout << x << "是第" << k << "个数" << endl;
else
cout << "查找失败" << endl;
cout << "还找另一个数吗?";
cin >> again;
} while (again != 'n');
return 0;
}
int Search(int a[],int n, int key) {
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (key == a[mid])
return mid + 1;
else if (key > a[mid]) {
low = mid + 1;
}
else
high = mid - 1;
}
return -1;
}
标签:high,cout,int,mid,二分法,查找,low,key 来源: https://www.cnblogs.com/GaoqiaoGaoqiao/p/16053433.html