#include <iostream>
#include <cstdlib>
using namespace std;
/*
* name : selection sort
* author : sangoly
* O(n^2)
* S(1)
* date : 2014/4/15
*/
int binary_search(int a[], int v, int low, int high)
{
if (low > high)
return -1;
int middle = (low+high)/2;
if (v == a[middle])
return middle;
else if (v < a[middle])
return binary_search(a, v, low, high-1);
else
return binary_search(a, v, low+1, high);
}
int main(int argc, const char **argv)
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
cout<<binary_search(a, 5, 0, 7)<<endl;
cout<<binary_search(a, 9, 0, 7)<<endl;
system("pause");
return 0;
}
二分查找
最新推荐文章于 2024-11-25 00:03:42 发布