Binary Search

Question:

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.


 

Soulution:

 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 }

 


 

Analysis:

采用二分法查找元素。算法复杂度为O(logN)。要求容器内元素已经按升序排列


 

 

Author: Cat

posted @ 2014-04-15 22:00  猫了个妖喵  阅读(143)  评论(0编辑  收藏  举报