waiting...'s Blog
二分查找
二分查找函数:
-
// 对于传入的以升序排列数组参数a,它以,则在下标为from和to之间查找值为num的数,找的则返回其下标;否则,返回-1
-
int binary_search(const int a[], int from, int to, int num)
-
{
-
if (from > to)
-
return -1;
-
-
int mid = (from + to) / 2;
-
if (a[mid] == num)
-
return mid;
-
else if (a[mid] < num)
-
return binary_search(a, mid + 1, to, num);
-
else
-
return binary_search(a, from, mid - 1, num);
-
}
完整代码:
-
#include <iostream>
-
#include <ctime>
-
#include <cstdlib>
-
using namespace std;
-
-
// 设置随机整数的种子
-
void rand_seed()
-
{
-
unsigned int seed = static_cast<unsigned int>(time(NULL));
-
srand(seed);
-
}
-
-
// 返回一个介于lower与upper之间的一个随机整数
-
int randInt(int lower, int upper)
-
{
-
return lower + rand() % (upper - lower + 1);
-
}
-
-
void print(const int a[], const int length)
-
{
-
for (int i = 0; i < length; i++)
-
cout << a[i] << " ";
-
cout << endl;
-
}
-
-
// 对于传入的以升序排列数组参数a,它以,则在下标为from和to之间查找值为num的数,找的则返回其下标;否则,返回-1
-
int binary_search(const int a[], int from, int to, int num)
-
{
-
if (from > to)
-
return -1;
-
-
int mid = (from + to) / 2;
-
if (a[mid] == num)
-
return mid;
-
else if (a[mid] < num)
-
return binary_search(a, mid + 1, to, num);
-
else
-
return binary_search(a, from, mid - 1, num);
-
}
-
-
int main()
-
{
-
const int length = 20;
-
const int lower = 1; // 随机数上限
-
const int upper = 20; // 随机数下限
-
int a[length];
-
-
rand_seed();
-
a[0] = 11;
-
for (int i = 1; i < length; i++)
-
a[i] = a[i - 1] + randInt(lower, upper);
-
-
print(a, length);
-
-
int num; // 待查找的数字
-
while (cin >> num)
-
{
-
int temp_index = binary_search(a, 0, length, num);
-
if (temp_index != -1)
-
cout << "a[" << temp_index << "] = " << a[temp_index] << endl;
-
else
-
cout << "未找到" << endl;
-
}
-
return 0;
-
}