Binary search algorithm example implemented in js_javascript skills
May 16, 2016 pm 03:19 PMThe 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] ? 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>
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.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CLIP-BEVFormer: Explicitly supervise the BEVFormer structure to improve long-tail detection performance

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions

Recommended: Excellent JS open source face detection and recognition project

Explore the underlying principles and algorithm selection of the C++sort function

Improved detection algorithm: for target detection in high-resolution optical remote sensing images

Can artificial intelligence predict crime? Explore CrimeGPT's capabilities

PHP algorithm analysis: efficient method to find missing numbers in an array

Application of algorithms in the construction of 58 portrait platform
