var arr = [1,2,4,6,9,10,12,15]; function searchKey(arr, key) { var mid = parseInt(arr.length/2); var midValue = arr[mid]; if(key === midValue){ return midValue; }else if(key > midValue){ return searchKey(arr.slice(mid+1), key); }else if(key < midValue){ return searchKey(arr.slice(0, mid), key); }else{ return false; } } function print(arr, key) { var res = searchKey(arr, key); if(typeof res === "number") { console.log("找到了"); }else{ console.log("呜呜,没找到!"); } } print(arr, 1);
缺点是不能打印出准确位置;
下面这种参考大神的写法;
var arr = [1,2,4,6,9,10,12,15]; function searchKey(arr, key) { var high = arr.length - 1; var low = 0,middle,midValue; while(low <= high) { middle = parseInt( (low + high) / 2 ); midValue = arr[middle]; if(midValue === key) { return middle; }else if(midValue > key){ high = middle - 1; }else if(midValue < key){ low = middle + 1; }else{ return "错误的参数"; } } return false; } function print(arr, key) { var res = searchKey(arr, key); if(typeof res === "number") { console.log("找到了,位置是" + res); }else{ console.log("呜呜,没找到!"); } } print(arr, 1);