实现:
/********************************************** 二分查找算法 by Rowandjj 2014/7/11 **********************************************/ #include<iostream> using namespace std; //二分查找算法,arr为待查数组,len为数组长度,target为待查元素 int binary_search(int arr[],int len,int target); int main() { int t; int arr[] = {-3,0,3,4,5,36,40,57,78,90}; int arr2[] = {-3,0,3,11}; cin>>t; cout<<binary_search(arr2,5,t)<<endl; return 0; } //确保数组有序且按非降序排列 int binary_search(int arr[],int len,int target) { int low = 0,high = len-1,middle; while(low <= high) { middle = low + ((high - low)>>1);//防溢出且高效.不推荐用middle = (high + low)/2 if(arr[middle] == target) { return middle; }else if(arr[middle] > target)//去前半部分找 { high = middle - 1; }else//arr[middle] < target,去后半部分找 { low = middle + 1; } } return -1; }
原文:http://blog.csdn.net/chdjj/article/details/37692781