function binarySearch(arr, key) {
    arr.sort((a,b) => a - b);

    let len = arr.length;
    let head = 0;
    let tail = len - 1;
    let mid = 0;

    while (head <= tail) {
        mid = Math.floor((head + tail) / 2);

        if (arr[mid] < key) {
            head = mid+1;
        } else if (arr[mid] > key) {
            tail = mid-1;
        } else {
            return arr[mid];
        }
    }

    return -1;
}

后脑勺
23 声望1 粉丝

一只有追求、有梦想、喜欢写出漂亮代码的程序猿儿