[Algorithms] Refactor a Linear Search into a Binary Search with JavaScript
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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));
以上是关于[Algorithms] Refactor a Linear Search into a Binary Search with JavaScript的主要内容,如果未能解决你的问题,请参考以下文章
[React] Refactor a connected Redux component to use Unstated
[React] Refactor a Class Component with React hooks to a Function
[React] Refactor a Stateful List Component to a Functional Component with React PowerPlug
转载:Why machine learning algorithms are hard to tune and how to fix it