首页 > 其他 > 详细

Binary Search

时间:2014-04-16 05:53:57      阅读:526      评论:0      收藏:0      [点我收藏+]

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:

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

 


 

Analysis:

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


 

 

Author: Cat

Binary Search,布布扣,bubuko.com

Binary Search

原文:http://www.cnblogs.com/kids-7/p/3667430.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!