首页 > 其他 > 详细

Summary: Binary Search

时间:2014-06-27 22:27:22      阅读:422      评论:0      收藏:0      [点我收藏+]

Iterative ways: 

 1 int binarySearch (int[] a, int x) {
 2    int low = 0;
 3    int high = a.length - 1;
 4    int mid;
 5 
 6    while (low <= high) {
 7       mid = (low + high) / 2;
 8       if (a[mid] < x) {
 9          low = mid + 1;
10       }   
11       else if (a[mid] > x) {
12          high = mid - 1;
13       }
14       else {
15          return mid;
16       } 
17    }              
18    return -1;
19 }

Recursive ways:

 1 int binarySearchRecursive (int[] a, int x, int low, int high) {
 2     if (low > high) return -1; //error
 3     
 4     int mid = (low + high) / 2;
 5     if (a[mid] < x) {
 6         return binarySearchRecursive(a, x, mid + 1, high);
 7     }
 8     else if (a[mid] > x) {
 9         return binarySearchRecursive(a, x, low, mid - 1);
10     }
11     else {
12         return mid;
13     }
14 }

 

Summary: Binary Search,布布扣,bubuko.com

Summary: Binary Search

原文:http://www.cnblogs.com/EdwardLiu/p/3811198.html

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