#include <iostream>
using namespace std;
int BinarySearch(const int a[], int key, int low, int high); // 折半查找
const int ArSize = 100;
int main()
{
int a[ArSize];
for (int i = 0; i < ArSize; i++)
{
a[i] = i * i + 1;
cout << a[i] << ((i + 1)%10 == 0 ? "\n" : " ");
}
char ch;
int searchkey;
cout << "Please enter a number to be checked:\n";
while (cin >> searchkey)
{
int b = BinarySearch(a, searchkey, 0, ArSize - 1);
if (b != -1)
cout << "It's a["<< b <<"]\n";
else
cout << "cannot found!\n";
cout << "Do you want to continue?(Y/N)";
cin >> ch;
if (ch == 'N' || ch == 'n')
break;
cout << "Please enter a number to be checked:\n";
}
return 0;
}
int BinarySearch(const int a[], int key, int low, int high) // 折半查找
{
int middle;
while (low <= high)
{
middle = (low + high)/2;
if (key == a[middle])
return middle;
else if (key < a[middle])
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}
return -1; // not found!
}
折半查找法(数列已升序)
最新推荐文章于 2024-08-12 00:08:19 发布