PHP binary find whether an array contains an element

Source: Internet
Author: User

Binary find whether an array contains an element, compatible positive and negative sequence, code implementation:

The

code is as follows:


<?php





$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 sequence


echo Search ($array, $searchValue);





//reverse order


Rsort ($array);


echo Search ($array, $searchValue);


This has been searched before, read the example of Baidu Encyclopedia (Java Implementation), there are some other technical home writing code, there are problems, there is no implementation, these people do not test to put out misleading people, we can go to search and see, yesterday free to write a share of their own.
This array, which does not consider the Non-key key, is primarily a method that can be extended if required.

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.