折半查找比较次数
对n个记录的有序表作折半查找,则查找次数如下表。(通过表格下方的按钮和输入框可设置正整数n的值)
查找成功 | 查找失败 | |
至少比较 | 1 | (int)log2(n+1) |
至多比较 | (int)(log2n)+1 | (int)(log2n)+1 |
实现功能的代码如下:
<table border="0" cellspacing="1" cellpadding="2"> <tbody> <tr> <td style="border: 1px solid #448844;" align="center" valign="middle"><span style="font-size: 18px;"> </span></td> <td style="border: 1px solid #448844;" align="center" valign="middle"><span style="font-size: 18px;">查找成功</span></td> <td style="border: 1px solid #448844;" align="center" valign="middle"><span style="font-size: 18px;">查找失败</span></td> </tr> <tr> <td style="border: 1px solid #448844;" align="center" valign="middle"><span style="font-size: 18px;">至少比较</span></td> <td style="border: 1px solid #448844;" align="center" valign="middle"><span style="font-size: 18px;">1</span></td> <td style="border: 1px solid #448844;" align="center" valign="middle"><span id="a12" style="font-size: 18px;"> (int)log<sub>2</sub>(n+1)</span></td> </tr> <tr> <td style="border: 1px solid #448844;" align="center" valign="middle"><span style="font-size: 18px;">至多比较</span></td> <td style="border: 1px solid #448844;" align="center" valign="middle"><span id="a21" style="font-size: 18px;">(int)(log<sub>2</sub>n)+1</span></td> <td style="border: 1px solid #448844;" align="center" valign="middle"><span id="a22" style="font-size: 18px;"> (int)(log<sub>2</sub>n)+1</span></td> </tr> </tbody> </table> <input type="button" value="-" onclick=' var n=parseInt(document.getElementById("nVal").value); if(isNaN(n)) n=0; n=(n>0?n-1:0); document.getElementById("nVal").value=n; document.getElementById("a12").innerHTML=Math.floor(Math.log(n+1)/Math.LN2); document.getElementById("a21").innerHTML=document.getElementById("a22").innerHTML=Math.floor(Math.log(n)/Math.LN2)+1; '> <input type="number" id="nVal" style="width:120px" placeholder="设置正整数n" onkeyup=' var n=parseInt(this.value); if(isNaN(n)) n=0; document.getElementById("a12").innerHTML=Math.floor(Math.log(n+1)/Math.LN2); document.getElementById("a21").innerHTML=document.getElementById("a22").innerHTML=Math.floor(Math.log(n)/Math.LN2)+1; '> <input type="button" value="+" onclick=' var n=parseInt(document.getElementById("nVal").value); if(isNaN(n)) n=0; ++n; document.getElementById("nVal").value=n; document.getElementById("a12").innerHTML=Math.floor(Math.log(n+1)/Math.LN2); document.getElementById("a21").innerHTML=document.getElementById("a22").innerHTML=Math.floor(Math.log(n)/Math.LN2)+1; '>
posted on 2019-11-09 23:12 Leisureeen 阅读(5773) 评论(0) 编辑 收藏 举报