function mergeSort($arr) {
$length = count($arr);
if ($length <= 1) {
return $arr;
}
$mid = (int)($length / 2);
$left = array_slice($arr, 0, $mid);
$right = array_slice($arr, $mid);
$left = mergeSort($left);
$right = mergeSort($right);
return merge($left, $right);
}
function merge($left, $right) {
$result = [];
$leftLength = count($left);
$rightLength = count($right);
$i = $j = 0;
while ($i < $leftLength && $j < $rightLength) {
if ($left[$i] <= $right[$j]) {
$result[] = $left[$i];
$i++;
} else {
$result[] = $right[$j];
$j++;
}
}
while ($i < $leftLength) {
$result[] = $left[$i];
$i++;
}
while ($j < $rightLength) {
$result[] = $right[$j];
$j++;
}
return $result;
}
// 示例使用
$numbers = [5, 2, 8, 12, 3];
$sortedNumbers = mergeSort($numbers);
print_r($sortedNumbers);