每次遍历数组的二分之一,找到结果则返回。
<?php
/*二分查找*/
function binarysearch($arr, $str, $model = "value") {
$count = count($arr);
$result = false;
if ($count <= 1) {
$result = checkitem($arr, $str, $model);
} else {
$end = ceil($count / 2);
$use_arr = array_slice($arr, 0, $end, true);
$result = checkitem($use_arr, $str, $model);
if (!$result) {
$arr = array_slice($arr, $end, count($arr) - $end, true);
$result = binarysearch($arr, $str, $model);
}
}
return $result;
}
function checkitem($arr, $str, $model = "value") {
var_dump($model);
foreach ($arr as $key => $value) {
switch ($model) {
case 'value':
if ($value == $str) {
return [$key => $value];
}
break;
case 'key':
if ($key == $str) {
return [$key => $value];
}
break;
}
}
return false;
}
$arr = ['test1', 1, 'test' => '2', 'test2', 'asd', 'qwe1'];
$arr1 = ['test1'];
$result = binarysearch($arr, "test", "key");
var_dump($result);
#输出
array(1) {
[0] =>
string(5) "test1"
}