#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 - low) * (key - array[low]) / (array[high] - array[low]);
if (array[mid] < key)
{
low = mid + 1;
}
else if(array[mid] > key)
{
high = mid - 1;
}
else
{
return mid;
}
}
return 0;
}