码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-12-23 11:10:46      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:rip   lse   cep   binary   bsp   play   element   list   .so   

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

标签:rip   lse   cep   binary   bsp   play   element   list   .so   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!