Home > Web Front-end > JS Tutorial > Binary search-JS implementation

Binary search-JS implementation

不言
Release: 2018-03-30 17:09:47
Original
1766 people have browsed it

This article will share with you the code for using js to implement binary search in an ordered array. Interested friends can take a look at this code

function binary-search(arr,key){
       var low=0,
           high=arr.length-1,
           mid=Math.floor((low+high)/2);
       while(low<=high){
           mid=Math.floor((low+high)/2);
           if(key==arr[mid]){
               return mid;
           }else if(key<arr[mid]){
               high=mid-1;
          }else{
              low=mid+1;
          }
      }
      return -1;
  }
Copy after login

Search in an ordered array

Related recommendations:

javascript - Using JS to implement the problem of deleting TABLE in the DOM

js to implement breakpoint debugging

JS implements code to determine whether the mouse is rolling



The above is the detailed content of Binary search-JS implementation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template