題幹:
回顧查找問題(參見聯繫2.1-3),注意到如果序列A已排好序,就可以將該序列的中點與v進行比較.
根據比較的結果,原序列中就有一半可以不用再做進一步的考慮了.
二分查找算法會重複這個過程,每次都將序列剩餘的部分規模減半
爲二分查找寫出迭代或遞歸的僞代碼
證明: 二分查找最壞情況運行時間爲θ(lgn)
附:考慮以下查找問題:
輸入: n個數的序列A=<a1,a2,...,an>和一個值v
輸出: 下標i使得v=A[i] 或者當v不在A中,v爲特殊值NIL
function findAction($param)
{
$value = fetch($param, 0, 0);
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
$total_length = $length = count($arr);
$find_index = ceil($length / 2) - 1;
while (true) {
$length = ceil($length / 2);
if ($find_index < 0) {
$find_index = 0;
}
if ($find_index > $total_length - 1) {
$find_index = $total_length - 1;
}
if ($arr[$find_index] > $value) {
if ($find_index == 0) {
echo 'NULL!' . PHP_EOL;
break;
}
$find_index -= $length;
continue;
} elseif ($arr[$find_index] < $value) {
if ($find_index == $total_length - 1) {
echo 'NULL!' . PHP_EOL;
break;
}
$find_index += $length;
continue;
} elseif ($arr[$find_index] = $value) {
echo $find_index . PHP_EOL;
break;
}
}
}
查找的過程是靠length/2來算的 最壞的情況是 按照輸入的一組數的長度不斷減半 直到只剩下1個數
在該情況下 計算的步驟數爲 以2爲底的輸入數字數量的對數
所以最壞情況運行時間爲θ(lgn)