Home >Web Front-end >JS Tutorial >Binary search algorithm example implemented in js_javascript skills
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] ? 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.