复制代码 代码如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript">
//window.alert(Math.floor(5.7)); //向下取整 输出5
//二分查找法 数组必须是有序的
function binarySeach(arr,findval,leftIndex,rightIndex){
//找到中间的值
var midIndex=Math.floor((leftIndex+rightIndex)/2);
var midval=arr[midIndex];
//防止无穷递归
if(leftIndex>rightIndex){
//说明找不到
document.writeln("找不到");
return ;
}
//进行查找
if(midval>findval){
//在左边找
binarySeach(arr,findval,leftIndex,midIndex-1);
}else if(midval<findval){
//说明往右边找
binarySeach(arr,findval,midIndex+1,rightIndex);
}else{
//找到了 输出或者返回
document.writeln("找到了,下标为:"+midIndex);
return ;
}
}
var arr=[1,3,12,21,24,44,54,67];
binarySeach(arr,67,0,arr.length-1);
</script>
</head>
<body></body>
</html>