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

有序查找——折半查找

时间:2017-03-30 12:55:42      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:int   []   logs   search   有序   下标   class   static   color   

  

 1 public static String binarySearch(int[] a, int num) {
 2         if (a.length == 0)
 3             return "Eroor";
 4         int start = 0;
 5         int end = a.length - 1;
 6         int mid = (start + end) / 2;
 7         while (start <= end) {
 8             if (num == a[mid]) {
 9                 return "所查数在数组的下标为" + mid;
10             } else if (num > a[mid]) {
11                 start = mid + 1;
12             } else if (num < a[mid]) {
13                 end = mid - 1;
14             }
15             mid = (start + end) / 2;
16         }
17         return "数组中无该数值";
18     }

递归实现:

public static String binarySearch(int[] arr, int num,int start,int end) {
        if (arr.length == 0 || end<start)
            return "Eroor";
    
        int mid = (start + end) / 2;
        if (num==arr[mid]) {
            return  "所查数在数组的下标为"+mid;
        }else if(num<arr[mid]) {
            return binarySearch(arr, num,start,mid-1);
        }else {
            return binarySearch(arr, num, mid+1, end);
        }
}

 

有序查找——折半查找

标签:int   []   logs   search   有序   下标   class   static   color   

原文地址:http://www.cnblogs.com/littlewriter/p/6645564.html

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