關於遞歸和迭代分別的時間複雜度,遞歸的時間複雜度是O(N),而迭代的時間複雜度是O(logN),由y=N 和Y=logN兩條曲線我們知道,一定是O(logN)比較優一些。本文主要和大家分享PHP二分法查找之遞歸和迭代詳解,希望能幫助大家。
以下是兩段程式碼,和傻瓜式測效率的程式碼。
<?php function dichotomyIterationSearch($arr, $n, $v) { $left = 0; $right = $n - 1; while ($left <= $right) { $middle = bcp(bcadd($right, $left), 2); if ($arr[$middle] > $v) { $right = $middle - 1; } elseif ($arr[$middle] < $v) { $left = $middle + 1; } else { return $middle; } } return -1; } $arr = []; for ($i=0;$i<300000;$i++){ $arr[] = $i; } list($first) = explode(" ",microtime()); echo dichotomyIterationSearch($arr,count($arr),35387);echo '<br>'; list($second) = explode(" ",microtime()); echo round($second - $first,5)*1000000; function dichotomyRecursionSearch($arr, $low, $high, $v) { $middle = bcp(bcadd($low, $high), 2); if ($low < $high) { if ($arr[$middle] > $v) { $high = $middle - 1; return dichotomyRecursionSearch($arr, $low, $high, $v); } elseif ($arr[$middle] < $v) { $low = $middle + 1; return dichotomyRecursionSearch($arr, $low, $high, $v); } else { return $middle; } } elseif ($high == $low) { if ($arr[$middle] == $v) { return $middle; } else { return -1; } } return -1; } $arr = []; for ($i=0;$i<300000;$i++){ $arr[] = $i; } echo "<br>"; list($first) = explode(" ",microtime()); echo dichotomyRecursionSearch($arr,0, count($arr),35387);echo '<br>'; list($second) = explode(" ",microtime()); echo round($second - $first, 5)*1000000;
相關推薦:
#以上是PHP二分法查找之遞歸與迭代詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!