Parsing PHP dichotomy Find out if an array contains an element _php tutorial

Source: Internet
Author: User
Binary method finds whether an array contains an element, is compatible with the pros and cons, and the code implements:
Copy CodeThe code is as follows:

$searchValue = (int) $_get[' key '];

function search (array $array, $value)
{
$max = count ($array)-1;
$min = 0;
$isAscSort = $array [$min] < $array [$max];

while (TRUE) {
$sum = $min + $max;
$midKey = (int) ($sum%2 = = 1? ceil ($sum/2): $sum/2);

if ($max < $min) {
return-1;
} else if ($value = = $array [$midKey]) {
return 1;
} else if ($value > $array [$midKey]) {
$isAscSort? $min = $midKey + 1: $max = $midKey-1;
} else if ($value < $array [$midKey]) {
$isAscSort? $max = $midKey-1: $min = $midKey +1;
}
}
}

$array = Array (
' 4 ', ' 5 ', ' 7 ', ' 8 ', ' 9 ', ' 10 ', ' 11 ', ' 12 '
);
Positive order
Echo Search ($array, $searchValue);

Reverse
Rsort ($array);
Echo Search ($array, $searchValue);

This previous search, read the example of the Baidu Encyclopedia (Java Implementation), there are some other technical house write code, there are problems, there is no implementation, these people do not test to put out misleading people, we can go to search to see, yesterday free to write a share to everyone.
This does not consider the non-sequential key array, mainly the method, if necessary, you can expand their own.

http://www.bkjia.com/PHPjc/327121.html www.bkjia.com true http://www.bkjia.com/PHPjc/327121.html techarticle Dichotomy to find whether an array contains an element, compatible with the reverse order, code implementation: Copy the Code as follows: PHP $searchValue = (int) $_get[' key '); function search (array $array, $va ...

  • 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.