Parsing PHP binary method to find whether an array contains a certain element_PHP tutorial

WBOY
Release: 2016-07-21 15:10:24
Original
945 people have browsed it

Binary method to find whether an array contains a certain element, compatible with forward and reverse order, code implementation:

Copy code The 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);                                       max < $min) {
                                                                                                                                                                                                                                     $array[$midKey]) {
               $isAscSort ? $min = $midKey+1 : $max = $midKey-1;
                                                                                                                                 🎜>            $isAscSort ? $max = $midKey-1 : $min = $midKey+1;
                                                                                                                  , '5', '7', '8', '9', '10', '11', '12'
);
// Positive sequence
echo search($array, $ searchValue);

// Reverse order
rsort($array);
echo search($array, $searchValue);


I have searched and seen this before The example of Baidu Encyclopedia (implementation of Java), as well as some codes written by other technical geeks, all have problems and are not implemented at all. These people release them without testing to mislead people. You can search and have a look. I was free yesterday. If you have nothing to do, I will write one myself and share it with everyone.
This array does not consider non-sequential keys. It is mainly a method. You can extend it yourself if necessary.




http://www.bkjia.com/PHPjc/327121.html

www.bkjia.com
true

http: //www.bkjia.com/PHPjc/327121.html
TechArticle

Binary method to find whether an array contains a certain element, compatible with forward and reverse order, code implementation: Copy the code and the code is as follows: ? php $searchValue = (int)$_GET['key']; function search(array $array, $va...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template