1 前提是数据事先已经排好顺序
2
2^20 = 100万多(就是1M)
2^30 = 10亿多(就是1G)
3 有趣的例子:兰州拉面
4 见案例(erfenchazhao.cpp)
//
// Created by z on 20-2-11.
// 二分查找算法演示
//
#include <iostream>
using namespace std;
// 函数声明 arg1:指向查找数组的指针 arg2:需要查找的数值 arg3:查找数组数值的个数 return:int 返回查找到的结果
int BinarySearch(int* a, const int x, const int n);
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int result = BinarySearch(arr, 76, 10);
if(result == -1)
cout << "没找到" << endl;
else
cout << "元素位于数组arr[" << result << "]中" << endl;
return 0;
}
// 函数定义
int BinarySearch(int* a, const int x, const int n)
{
int low, high, mid;
low = 0, high = n - 1;
while(low <= high) // 折半还没结束
{
mid = (low + high) / 2; // 折半
if(a[mid] == x)
return mid; // 如果找到了,返回对应的下标
else if (a[mid] < x)
low = mid + 1;
else if (a[mid] > x)
high = mid - 1;
}
return -1; // 如果没找到,返回-1
}