Example of PHP array search function based on the binary method [loop and recursive algorithms], binary Recursion

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.