PHP based on the binary method to implement array lookup function example explained

Source: Internet
Author: User
This article mainly introduces PHP based on the binary method to realize the array lookup function, combined with the example form analysis of while loop and recursive call algorithm implementation of binary search function of the relevant implementation skills, the need for friends can refer to the following

In this paper, we describe the implementation of the array lookup function based on the binary method of PHP. 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:

Articles you may be interested in:

A detailed description of classes and objects in PHP

PHP Single file and multi-file upload instance explanation

The principle analysis of PHP Multi-person module development

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.