zoukankan      html  css  js  c++  java
  • [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));
  • 相关阅读:
    js的元素对象
    js实现在末尾添加节点
    js实现点击增加文本输入框
    js的DOM对象
    js其它
    js实现99乘法表
    js
    http的六种请求方法
    11.进制
    10.Debug
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10163225.html
Copyright © 2011-2022 走看看