欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

常见的查找算法----折半查找(JavaScript实现)

程序员文章站 2022-03-15 11:43:29
...

递归实现

    function binarySearch (arr, element) {
        return searchSort(arr, element, 0, arr.length-1);
    }
    function searchSort(arr, element, left, right) {
        if(left > right) {
            return -1;
        }
        var mid = Math.floor((left + right) / 2);
        if(arr[mid] == element) {
            return mid;
        }else if(arr[mid] > arr[left]) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
        return searchSort(arr, element, left, right);
    }

    var arr = [17,31,45,80,67,45,56,79];
    console.log(binarySearch(arr, 100));

非递归实现

function binarySearch (arr, element) {
    if(!arr) {
        return -1}
    var left = 0;
    var right = arr.length - 1;
    var mid;
    while(left <= right) {
        mid = Math.floor((left+right)/2);
        if(arr[mid] == element) {
            return mid;
        } else if(arr[mid] > element) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return -1;
}
var arr = [17,31,45,80,67,45,56,79];
console.log(binarySearch(arr, 100));