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