$arr = [99, 1, 2, 3, 4, 5, 19, 6, 7, 8, 9];
$arr = paopao($arr);
print_r($arr);
echo binary_search($arr, 6) . PHP_EOL;
//冒泡排序
function paopao($arr)
{
$count = count($arr);
for ($i = 0; $i < $count - 1; $i++) {
for ($j = $i + 1; $j < $count; $j++) {
if ($arr[$i] > $arr[$j]) {
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
}
}
return $arr;
}
//折半查找
function binary_search($arr, $target)
{
$left = 0;
$right = count($arr) - 1;
while (true) {
if ($left <= $right) {
$mid = intval($left + ($right - $left) / 2);
if ($arr[$mid] == $target) {
return $mid;
} elseif ($arr[$mid] < $target) {
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
}
return -1;
}
网友评论