js 二分法

/**

* @param {number[]} nums

* @param {number} target

* @return {number}

*/

var search = function(nums, target) {

    let start = 0, end = nums.length - 1

    while (start < end) {

        let mid = Math.floor((start + end) / 2)

        if (nums[mid] == target) {

            return mid

        } else if (nums[mid] > target) {

            end = mid - 1

        } else if(nums[mid] < target){

            start = mid + 1

        }

    }

    return -1

};

let eg_arr = [-1,0,3,5,9,12];

let eg_value = 6;

console.log(search(eg_arr,eg_value));

你可能感兴趣的:(js 二分法)