Example of PHP array search function based on the binary method [loop and recursive algorithms], binary Recursion
This example describes how PHP performs array search based on the binary method. We will share this with you for your reference. The details are as follows:
Binary classification. Use the while loop method and the recursive call method respectively.
<? Php // The use of the binary array must be ordered, or ascending, or descending $ arr = array (1, 3, 5, 7, 9, 13 ); // recursive call (better understanding function bsearch_r ($ v, $ arr, $ low, $ high) {if ($ low> $ high) {// first determine the end condition return-1;} $ 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); // 0 echo '
Running result: