With regard to the time complexity of recursion and iteration, the time complexity of recursion is O (N), and the time complexity of Iteration is O (logn), the two curves of y=n and Y=logn we know, must be O (logn) better. This article is mainly to share with you the PHP dichotomy search recursive and iterative detailed, hope to help everyone.
Here are two pieces of code, and the code for the idiot-type measurement efficiency.
<?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;
Related recommendations:
Two-part method to find the introduction and examples
Introduction to how JavaScript uses the dichotomy method to find data
Find the elements in an array by dichotomy