时间:2020/1/23
// 二分查找法.cpp
#include <iostream>
using namespace std;
int binsearch(int x, int v[], int n)
{
int low, high, mid;
low = 0; high = n - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (x < v[mid])
{
high = mid - 1;
}
else if (x > v[mid])
{
low = mid + 1;
}
else
return mid;
}
return -1;
}
int main()
{
int a[20005];
int m, i, n, wei, b;
cout << "enter the length of array";
cin >> m;
cout << "enter the array";
for (i = 0; i < m; i++)
{
cin >> a[i];
}
cout << "enter the check number";
cin >> b;
wei = binsearch(b, a, m);
if (wei == -1)
{
cout << "not found" << endl;
}
else
{
cout << "position is " << wei << endl;
}
return 0;
}