AILINGANGEL / algorithm

常见算法解析
0 stars 0 forks source link

二分查找 #7

Open AILINGANGEL opened 5 years ago

AILINGANGEL commented 5 years ago

1.排序数组实现二分查找

var search = function(nums, target) {
    let low = 0;
    let high = nums.length - 1;
    while(low <= high) {
        let mid = Math.floor((low + high)/2);
        if(nums[mid] === target) {
            return mid;
        } else if (nums[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return -1;
};