二分搜索
递归实现
function __binarySearch(arr, l, r, e){
if (l > r) {
return;
}
var middle = Math.floor(l + (r - l) / 2);
console.log('finding ……', middle, e, arr[middle]);
if (e < arr[middle]) {
return __binarySearch(arr, l, middle - 1, e);
} else if (e > arr[middle]) {
return __binarySearch(arr, middle + 1, r, e);
} else {
return middle;
}
return -1;
}
function binarySearch(arr, e){
return __binarySearch(arr, 0, arr.length - 1, e);
}
var arr = [1, 2, 3, 4, 5];
var res = binarySearch(arr, 5);
console.log('find ok : ', res);
非递归实现
function binary_search(arr, key) {
var low = 0,
high = arr.length - 1;
while(low <= high){
var mid = parseInt((high + low) / 2);
if(key == arr[mid]) {
return mid;
} else if(key > arr[mid]) {
low = mid + 1;
} else if(key < arr[mid]) {
high = mid -1;
} else{
return -1;
}
}
};
var arr = [1,2,3,4,5,6,7,8,9,10,11,23,44,86];
var result = binary_search(arr, 10);
console.log(result);