Binary method to find whether an array contains a certain element, compatible with forward and reverse order, code implementation:
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);
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);
I have searched this before, and I have seen examples from Baidu Encyclopedia (implementation of Java), and some codes written by other technical geeks. They all have problems and are not implemented at all. These people release them without testing to mislead people. You can search After searching, I had nothing to do yesterday so I wrote one to share with everyone.
This array does not take into account non-sequential keys. It is mainly a method. You can expand it yourself if necessary.
http://www.bkjia.com/PHPjc/371967.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/371967.htmlTechArticleBinary method to find whether an array contains a certain element, compatible with forward and reverse order, code implementation: The code is as follows: ?php $ searchValue = (int)$_GET['key']; function search(array $array, $value) { $max...