标签:二分查找
#include <iostream>
using namespace std;
int find_val(int a[],int n,int val)
{
int low = 0;
int high = n-1;
while(low<=high)
{
//mid=(high+low)/2;//可能溢出。
int mid = low+(high-low)/2;
if(a[mid]>val)
{
high = mid-1;
}
else if(a[mid]<val)
{
low = mid+1;
}
else
{
return a[mid];
}
}
return -1;
}
int main()
{
int a[]={1,2,3,4,5,6,7,8,9};
cout<<find_val(a,sizeof(a)/sizeof(int),6)<<endl;;
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:二分查找
原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/48041241