"JavaScript method" binary thinking and looking for code implementation

Find the binary thinking

  • First, start the search from the middle of the elements of an ordered array, if that element happens to be the target element (ie the element you want to find), the search process ends, otherwise the next step.
  • If the target element is greater than or less than the intermediate element, in that half of the intermediate region larger or smaller than an array lookup element, then repeating the first step of the operation.
  • If a step in the array is empty, then could not find the target element

Code

  • Non-recursive
// 非递归算法
function binary_search(arr, key) {
    let low = 0;
    let high = arr.length - 1;
    while(low <= high){
        let mid = parseInt((high + low) / 2);
        if(key === arr[mid]){
            return  mid;
        }else if(key > arr[mid]){
            low = mid + 1;
        }else if(key < arr[mid]){
            high = mid -1;
        }else{
            return -1;
        }
    }
}
  • Recursive
// 递归算法
function binary_search(arr,low, high, key) {
    if (low > high){
        return -1;
    }
    let mid = parseInt((high + low) / 2);
    if(arr[mid] === key){
        return mid;
    }else if (arr[mid] > key){
        high = mid - 1;
        return binary_search(arr, low, high, key);
    }else if (arr[mid] < key){
        low = mid + 1;
        return binary_search(arr, low, high, key);
    }
};

Original link: https://github.com/qianbin01/frontend_train#sort

Guess you like

Origin www.cnblogs.com/yuanchao-blog/p/10991583.html