Merge pull request #278 from wangchengtao/master
修复 $this 引用错误, 添加相应注释, 调整部分代码, 与原文同步
This commit is contained in:
commit
ffc5da2368
@ -1,40 +1,48 @@
|
||||
<?php
|
||||
/*
|
||||
* 归并排序
|
||||
*/
|
||||
|
||||
$arr = [4, 5, 6, 1, 3, 2];
|
||||
$length = count($arr);
|
||||
$arr = [4, 5, 6, 1, 3, 2];
|
||||
$length = count($arr);
|
||||
|
||||
$p = 0;
|
||||
$r = $length - 1;
|
||||
$p = 0;
|
||||
$r = $length - 1;
|
||||
|
||||
$result = $this->mergeSort($arr, $p, $r);
|
||||
$result = mergeSort($arr, $p, $r);
|
||||
|
||||
var_dump($result);
|
||||
var_dump($result);
|
||||
|
||||
|
||||
//递归调用,分解数组
|
||||
function mergeSort(array $arr, $p, $r)
|
||||
{
|
||||
return mergeSortRecursive($arr, $p, $r);
|
||||
}
|
||||
|
||||
// 递归调用函数
|
||||
function mergeSortRecursive(array $arr, $p, $r)
|
||||
{
|
||||
// 递归终止条件
|
||||
if ($p >= $r) {
|
||||
return [$arr[$r]];
|
||||
}
|
||||
|
||||
// 取 p 到 r 之间的中间位置 q
|
||||
$q = (int)(($p + $r) / 2);
|
||||
|
||||
$left = $this->mergeSort($arr, $p, $q);
|
||||
$right = $this->mergeSort($arr, $q + 1, $r);
|
||||
return $this->merge($left, $right);
|
||||
// 分治递归
|
||||
$left = mergeSortRecursive($arr, $p, $q);
|
||||
$right = mergeSortRecursive($arr, $q + 1, $r);
|
||||
return merge($left, $right);
|
||||
}
|
||||
|
||||
//合并
|
||||
// 合并
|
||||
function merge(array $left, array $right)
|
||||
{
|
||||
$tmp = [];
|
||||
|
||||
$i = 0;
|
||||
|
||||
$j = 0;
|
||||
$i = $j = 0;
|
||||
|
||||
$leftLength = count($left);
|
||||
|
||||
$rightLength = count($right);
|
||||
|
||||
do {
|
||||
@ -43,24 +51,23 @@ function merge(array $left, array $right)
|
||||
} else {
|
||||
$tmp[] = $right[$j++];
|
||||
}
|
||||
|
||||
} while ($i < $leftLength && $j < $rightLength);
|
||||
|
||||
|
||||
$start = $i;
|
||||
$end = $leftLength;
|
||||
$copyArr = $left;
|
||||
|
||||
// 判断哪个子数组中有剩余的数据
|
||||
if ($j < $rightLength) {
|
||||
$start = $j;
|
||||
$end = $rightLength;
|
||||
$copyArr = $right;
|
||||
}
|
||||
|
||||
for (; $start < $end; $start++) {
|
||||
$tmp[] = $copyArr[$start];
|
||||
}
|
||||
// 将剩余的数据拷贝到临时数组 tmp
|
||||
do {
|
||||
$tmp[] = $copyArr[$start++];
|
||||
} while ($start < $end);
|
||||
|
||||
return $tmp;
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user