Skip to content

Commit

Permalink
Merge pull request wangzheng0822#278 from wangchengtao/master
Browse files Browse the repository at this point in the history
修复 $this 引用错误, 添加相应注释, 调整部分代码, 与原文同步
  • Loading branch information
wangzheng0822 authored Mar 20, 2019
2 parents 674af74 + 8edc48d commit ffc5da2
Showing 1 changed file with 29 additions and 22 deletions.
51 changes: 29 additions & 22 deletions php/12_sort/mergeSort.php
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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;

}

0 comments on commit ffc5da2

Please sign in to comment.