#include <iostream>
int init_array(int *array, int n);
int binary_search(int *array, int n, int key);
int main()
{
int array[17];
int key;
init_array(array, 17);
std::cout << "请输入要查找的数字(0-16):" << std::endl;
std::cin >> key;
std::cout << "要查找的数字为:" << array[binary_search(array, 17, key)] << std::endl;
return 0;
}
int init_array(int *array, int n)
{
for (int i = 0; i < n; ++i)
{
array[i] = i;
}
return 0;
}
int binary_search(int *array, int n, int key)
{
int low, high, mid;
low = 1;
high = n;
while (low <= high)
{
mid = (low + high) / 2;
if (array[mid] < key)
{
low = mid + 1;
}
else if(array[mid] > key)
{
high = mid - 1;
}
else
{
return mid;
}
}
return 0;
}
该算法前提数组里面内容排列是有序的
算法思路:首先mid取数组中间的位置 如果要查找的key比数组中元素小那么就high = mid - 1 反之 low = mid + 1
全部代码如下: