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

Summary: Binary Search

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

标签:style   blog   color   c   div   5   

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

标签:style   blog   color   c   div   5   

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

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