前提:数组是有序的
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
var resultArray = [5,3,10,7,6];
//标记的思想
function sortNum(a, b){
return a-b;
}
resultArray = resultArray.sort(sortNum);
console.log(resultArray);
var min = 0;
var max = resultArray.length - 1;
var index = -1;//用来记录最终找到的结果
for (var i = 0;i < resultArray.length / 2;i++) {
//需要查找的下标
var middle = parseInt((min + max) / 2);
//console.log(middle);
if (resultArray[middle] == 7) {
index = middle;
console.log(index);
break;
}else if(resultArray[middle] < 7){
min = middle + 1;
}else{
max = middle;
}
}
if (index != -1) {
console.log("7这个元素在数组的下标为:" + index);
}
</script>
</html>