This article mainly introduces PHP based on
two pointsmethod to realize the function of array lookup, and to analyze the implementation of while loop and recursive call algorithm with instance form
two pointsFind the relevant implementation skills of the function, the need for friends can refer to this article, the example of this article describes PHP based on
two pointsmethod to implement the array lookup function. Share to everyone for your reference, as follows:
Dichotomy method. Methods that use the while loop and recursive invocations, respectively.
<?php//the use of the array must be ordered, or ascending, or descending $arr = Array (1, 3, 5, 7, 9, 13);//recursive invocation (compared to better understanding function Bsearch_r ($v, $arr, $low, $high) {if ($low > $high) {//return-1 to determine the end condition first; } $i = Intval (($high + $low)/2); if ($arr [$i] > $v) {return Bsearch_r ($v, $arr, $low, $i-1);//recursion} else if ($arr [$i] < $v) {return Bsearch_r ( $v, $arr, $i +1, $high); } else {return $i; }}echo bsearch_r (1, $arr, 0, Count ($arr)-1);//0echo '
Operation Result: