[Algorithms] Refactor a Linear Search into a Binary Search with JavaScript

Binary search is an algorithm that accepts a sorted list and returns a search element from the list. It provides a dramatic performance boost over searching linearly through a list for an element. Let’s play around number of iterations required for each search method to complete and refactor our linear list search into a binary search function.

let items = [10,5,6,7,1,3,2,4];
items = items.sort((a,b) => {return a-b})

function binarySearch (list, item = null) {
    let low =  0;
    let high = list.length;
    let counter = 0;

    while (low <= high) {
        counter++;
        console.log(counter)
        let med = Math.floor((low + high) / 2)
        let guess = list[med];
        if (guess === item) return true;
        if (guess > item) high = med - 1;
        else low = med + 1
    }

    return null
}

console.log(binarySearch(items,3));
原文地址:https://www.cnblogs.com/Answer1215/p/10163225.html