首页 > 其他 > 详细

Algorithm | Binary Search

时间:2014-06-07 11:19:28      阅读:362      评论:0      收藏:0      [点我收藏+]

1. 普通的二分查找

2. 查找最左边的值

3. 查找最右边的值

Worst case performance: O(log n)
Best case performance: O(1)
Average case performance: O(log n)
Worst case space complexity: O(1)

bubuko.com,布布扣
 1 class BinarySearch {
 2 public:
 3     BinarySearch() {}
 4     int find(Sort& arr, int value) {
 5         int l = 0, h = arr.size() - 1; 
 6         while (l <= h) {
 7             int mid = (l + h) / 2;
 8             if (value == arr[mid]) return mid;
 9             else if (value > arr[mid]) {
10                 l = mid + 1;    
11             } else {
12                 h = mid - 1;
13             }
14         }
15         return -1;
16     }
17 
18     int findLeftMost(Sort& arr, int value) {
19         int l = 0, h = arr.size() - 1; 
20         while (l <= h) {
21             int mid = (l + h) / 2;
22             if (arr[mid] >= value) {
23                 h = mid - 1;
24             } else {
25                 l = mid + 1;    
26             }
27         }
28         if (l >= arr.size() || arr[l] != value) return -1;
29         else return l;
30     }
31     
32     int findRightMost(Sort& arr, int value) {
33         int l = 0, h = arr.size() - 1; 
34         while (l <= h) {
35             int mid = (l + h) / 2;
36             if (arr[mid] > value) {
37                 h = mid - 1;
38             } else {
39                 l = mid + 1;    
40             }
41         }
42         if (h < 0 || arr[h] != value) return -1;
43         else return h;
44     }
45 };
bubuko.com,布布扣

 网上看到说,mid=(l+h)/2可能会溢出,所以要写成mid=l + (h-l)/2.

Algorithm | Binary Search,布布扣,bubuko.com

Algorithm | Binary Search

原文:http://www.cnblogs.com/linyx/p/3770209.html

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