<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <title>二分算法示例,针对按顺序排好的索引数组</title> </head> <body> </body> </html>
var binarySearch = function (arr, start, stop, num) { if (stop - start == 1) { if (arr[start] == num) { return start; } if (arr[stop] == num) { return stop; } return -1; } var center = Math.floor((start + stop) / 2); if (num != arr[center]) { return num > arr[center] ? binarySearch(arr, center, stop, num) : binarySearch(arr, start, center, num); } return center; } var arr = [1, 4, 6, 12, 15, 20, 38, 44]; console.log(arr) console.log('find 2 : ' + binarySearch(arr, 0, arr.length, 2)); console.log('find 38 : ' + binarySearch(arr, 0, arr.length, 38)); console.log('find 15 : ' + binarySearch(arr, 0, arr.length, 15));