首页 > 代码库 > 有序查找——折半查找

有序查找——折半查找

  

 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);
        }
}

 

有序查找——折半查找