二分搜索很简单,本来很简单的东西,自己动手再纸上手写了一段代码,以为没有问题,然后放在电脑里一测试居然有问题,看来任何简单的代码都不能太大意。
#include <iostream>
int binarysearch(int datas[], int x, int low, int high)
{
if (low > high)
{
return -1 ;
}
int mid = (int)(low + high) * 0.5;
if (x == datas[mid])
{
return mid;
}
else if (datas[mid] > x)
{
binarysearch(datas, x, low, mid - 1);
}
else
{
binarysearch(datas, x, mid + 1, high);
}
}
void main()
{
int datas[10] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
int location = binarysearch(datas, 10, 0, 9);
std::cout << "location:" << location << std::endl;
}