js实现的二分查找算法实例
m1870164 人气:0本文实例讲述了js实现的二分查找算法。分享给大家供大家参考,具体如下:
<!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>
运行结果为:
-1
希望本文所述对大家JavaScript程序设计有所帮助。
加载全部内容