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

Binary search-JS implementation

不言
不言Original
2018-03-30 17:09:471723browse

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

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!

Statement:
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