二分查找

 二分查找(折半查找)

 [要求] 1. 必须采用顺序存储结构; 2.必须按关键字大小有序排列。

/**
     * 折半查找
     * @param arr
     * @param searchValue
     * @return
     */
    public static int binarySearch(int[] arr, int searchValue) {
        if(arr == null) {
            return -1;
        }
        
        int low = 0;
        int high = arr.length -1;
        
        while(low <= high) {
            int midIndex = (low + high)/2;
            
            if(arr[midIndex] == searchValue) {
                return midIndex;
            }else if(arr[midIndex] > searchValue) {
                high = midIndex - 1;
            }else{
                low = midIndex + 1;
            }
            
        }
        
        return -1;
        
    }
    
    
    /**
     * 二分查找,特殊实现
     * @param arr
     * @param searchValue
     * @param first
     * @param last
     * @return
     */
    public static int binarySearch(int[] arr, int searchValue, int first,int last) {
        if(arr == null) {
            return -1;
        }
        
        if(searchValue < arr[first] || searchValue > arr[last]) {
            return -1;
        }
        
        int midIndex = (first+last)/2;
        
        if(searchValue < arr[midIndex]) {
            return binarySearch(arr, searchValue, first, midIndex-1);
        }else if(searchValue > arr[midIndex]){
            return binarySearch(arr, searchValue, midIndex + 1, last);
        }else {
            return midIndex;
        }
        
    }
    

 

posted on 2018-03-27 19:06  齊帥  阅读(120)  评论(0编辑  收藏  举报

导航