二分查找的一个重要前提:表中的元素必须有序,且仅限于顺序存储结构。
include <iostream>
using namespace std;
int BinarySearch(int *a, int n, int key);
//注意:表中的元素必须有序,且仅限于顺序存储结构
int BinarySearch(int *a, int n, int key)
{
int low = 0;
int high = n - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (a[mid] == key)
{
return mid;
}
if (key < a[mid]) //往左区间找
{
high = mid - 1;
}
else //往右区间找
{
low = mid + 1;
}
}
return -1;
}
int main()
{
int a[11] = {5, 16, 20, 27, 30, 36, 44, 55, 60, 67, 71};
int n = 11;
cout << "search 27 = " << BinarySearch(a, n, 27) << endl;
cout << "search 65 = " << BinarySearch(a, n, 65) << endl;
cout << system("pause");
return 0;
}
参考资料:《数据结构(C语言版)》p166-p169