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.