码迷,mamicode.com
首页 > 其他好文 > 详细

Algorithm | Binary Search

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

标签:c   style   class   blog   code   java   

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

标签:c   style   class   blog   code   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!