首页 > 编程语言 > 详细

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

时间:2018-12-23 10:50:05      阅读:142      评论:0      收藏:0      [点我收藏+]

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));

 

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

原文:https://www.cnblogs.com/Answer1215/p/10163225.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!