二分查找

代码:

 */
static int binarySerach(int[] array, int key) {
    int low = 0;
    int high = array.length - 1;
    // 这里必须是 <=
    while (low <= high) {
        int mid = (low + high) / 2;
        if (array[mid] == key) {
            return mid;
        }
        else if (array[mid] < key) {
            low = mid + 1;
        }
        else {
            high = mid - 1;
        }
    }
    return -1;
}

复杂度:O(logN)

例如:8到4到2到1

posted on 2018-09-05 17:01  Aaron12  阅读(94)  评论(0编辑  收藏  举报

导航