归并排序
小于 1 分钟
归并排序
归并排序(Merge Sort)
归并排序是建立在归并操作上的一种有效的排序算法。 该算法是采用分治法的一个非常典型的应用。 将已有序的子序列合并,得到完全有序的序列; 即先使每个子序列有序,再使子序列段间有序。 若将两个有序表合并成一个有序表,称为2路归并。
算法描述
- 把长度为n的输入序列分成两个长度为n/2的子序列;
- 对这两个子序列分别采用归前排序;
- 将两个排序好的子序列合并成一个最终的排序序列。
动图演示
代码实现
$numbers = [20, 40, 60, 80, 30, 70, 90, 10, 50, 0, 5];
/**
* @param $numbers
* @return mixed
* 归并排序
*/
function mergeSort($numbers)
{
$length = count($numbers);
if ($length < 2) return $numbers;
$middle = floor($length / 2);
$left = array_slice($numbers, 0, $middle);
$right = array_slice($numbers, $middle);
return merge(mergeSort($left), mergeSort($right));
}
function merge($left, $right)
{
$result = [];
while (count($left) > 0 && count($right) > 0) {
if ($left[0] <= $right[0]) {
array_push($result, array_shift($left));
} else {
array_push($result, array_shift($right));
}
}
while (count($left)) {
array_push($result, array_shift($left));
}
while (count($right)) {
array_push($result, array_shift($right));
}
return $result;
}
$numbers = mergeSort($numbers);
var_dump($numbers);