时间:2021-07-01 10:21:17 帮助过:18人阅读
以下是两段代码,和傻瓜式测效率的代码。
<?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;
相关推荐:
二分法查找介绍及实例详解
JavaScript如何使用二分法查找数据的方法介绍
二分法查找数组中的元素
以上就是PHP二分法查找之递归和迭代详解的详细内容,更多请关注Gxl网其它相关文章!