Given an interger X and intergers A0,A1,……,A(n-1), which are presorted and already in memory,find i such that Ai=X, or return i=-1 if X is not in the input.
1 template <typename T> 2 int binarySearch(<const vector<T> & a, const T &x) 3 { 4 int low=0,high=a.size()-1; 5 6 while(low<=high) 7 { 8 int mid=(low+high)/2; 9 if (a[mid]<x) 10 low=mid+1; 11 else if (a[mid]>x) 12 high = mid-1; 13 else return mid; 14 } 15 return -1; 16 }
采用二分法查找元素。算法复杂度为O(logN)。要求容器内元素已经按升序排列
Author: Cat
原文:http://www.cnblogs.com/kids-7/p/3667430.html