Posted in Javascript onJanuary 21, 2016
本文实例讲述了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程序设计有所帮助。
js实现的二分查找算法实例
- Author -
m1870164声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@