二分查找

/**
 * 数组必须是已排序
 * @param key 查找key
 * @param array 数组
 * @return
 */
public static int rank(int key, int[] array) {
    int low = 0;
    int high = array.length - 1;
    
    while (low <= high) {
        int mid = low + (high - low) / 2;
        
        if (key < array[mid]) {
            high = mid - 1;
        } else if (key > array[mid]) {
            low = mid - 1;
        } else {
            return mid;
        }
    }
    
    return -1;
}

 

posted @ 2019-03-04 13:07  yixiu868  阅读(97)  评论(0编辑  收藏  举报