Home > Web Front-end > JS Tutorial > body text

Binary search algorithm example implemented in js_javascript skills

WBOY
Release: 2016-05-16 15:19:06
Original
1190 people have browsed it

The example in this article describes the binary search algorithm implemented in js. Share it with everyone for your reference, the details are as follows:

<!DOCTYPE html>
<html>
  <head>
    <title>demo</title>
    <style type="text/css">
    </style>
    <script type="text/javascript">
      var binarySearch = function(array, start, stop, num) {
        if(stop - start == 1) {
          if(array[start] == num) {
            return start;
          }
          if(array[stop] == num) {
            return stop;
          }
          return -1;
        }  
        var center = Math.floor((start + stop)/2);
        if(num != array[center]) {
          return num > array[center] &#63; binarySearch(array, center, stop, num) 
            : binarySearch(array, start, center, num);
        }
        return center;
      }
      var array = [1,4,6,12,15,20];
      document.writeln(binarySearch(array, 0, array.length, 2));
    </script>
  </head>
  <body>
  </body>
</html>
Copy after login

The running result is:

-1

Readers who are interested in more content related to JavaScript algorithms can check out the special topics on this site: "Summary of JavaScript data structures and algorithm techniques", "Summary of JavaScript traversal algorithms and techniques" And "Summary of JavaScript sorting algorithm"

I hope this article will be helpful to everyone in JavaScript programming.

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!