递归
function binary_search(arr, low, high, key) {
if (low > high) {
return -1;
}
var mid = parseInt((high+low) / 2);
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
high = mid - 1;
return binary_search(arr, low, high, key);
} else if (arr[mid] < key) {
low = mid 1;
return binary_search(arr, low, high, key);
}
}
非递归
function binary_search(arr, key) {
var low = 0;
var high = arr.length - 1;//定义变量为数组两端的下标
while(low <= high) {
var mid = parseInt((high + low) /2);//步骤1
if(key == arr[mid]) {
return mid;//步骤2
} else if(key > arr[mid]) {
low = mid + 1;//步骤3
} else {
high = mid -1;//步骤4
}
}
return -1//步骤6
}