任务一和扩展:参考这篇 C1任务04
参考了上面这篇之后,发现最后一题有一个小bug,于是修改得到如下
var array = [8, 7, 12, 1,5, 0, 6, 9, 2];
var key = 6; //假设要查找的是6
array.sort((a, b) => {
return a - b;
}); //js中的sort写回调函数,不然就是按照字符编码来比大小了
var result = binarySearch(array, key);
if (-1 === result) {
console.log("未查找到" + key);
} else {
console.log("查找到" + key + "在array排序后索引位置为:" + result);
}
//函数二分查找,找到返回索引,未找到返回-1
function binarySearch(array, key) {
var index = -1;
var start = 0;
var end = array.length - 1;
var middle = Math.floor((end + start) / 2);
while (start !== end) {
if (key < array[middle]) {
end = middle - 1;
middle = Math.floor((end + start) / 2);
continue
}
if (key > array[middle]) {
start = middle + 1;
if (key === array[middle + 1]) {
return middle + 1
}
middle = Math.floor((end + start) / 2);
continue
}
if (key === array[middle]) {
return middle;
}
}
return index;
}
输出效果: