From 5d140669a2931ef487e6a820a25640d3928a768b Mon Sep 17 00:00:00 2001 From: yangmin Date: Thu, 25 Oct 2018 16:08:13 +0800 Subject: [PATCH 1/2] php 12_merge_sort --- php/12_sort/mergeSort.php | 63 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 php/12_sort/mergeSort.php diff --git a/php/12_sort/mergeSort.php b/php/12_sort/mergeSort.php new file mode 100644 index 0000000..e32ff52 --- /dev/null +++ b/php/12_sort/mergeSort.php @@ -0,0 +1,63 @@ +mergeSort($arr, $p, $r); + + var_dump($result); + + +//递归调用,分解数组 +function mergeSort(array $arr, $p, $r) +{ + if ($p >= $r) { + return [$arr[$r]]; + } + $q = (int)(($p + $r) / 2); + + $left = $this->mergeSort($arr, $p, $q); + $right = $this->mergeSort($arr, $q + 1, $r); + return $this->merge($left, $right); +} + +//合并 +function merge(array $left, array $right) +{ + $tmp = []; + + $i = 0; + + $j = 0; + + $leftLength = count($left); + + $rightLength = count($right); + + do { + if ($left[$i] <= $right[$j]) { + $tmp[] = $left[$i++]; + } else { + $tmp[] = $right[$j++]; + } + + } while ($i < $leftLength && $j < $rightLength); + + $start = $i; + $end = $leftLength; + + if ($j < $rightLength) { + $start = $j; + $end = $rightLength; + } + + for (; $start < $end; $start++) { + $tmp[] = $right[$start]; + } + + return $tmp; + +} \ No newline at end of file From bfb3dd581f76815a7723ba7c11fa1d19859dcd3e Mon Sep 17 00:00:00 2001 From: yangmin Date: Thu, 25 Oct 2018 17:03:39 +0800 Subject: [PATCH 2/2] fix mergeSort --- php/12_sort/mergeSort.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/php/12_sort/mergeSort.php b/php/12_sort/mergeSort.php index e32ff52..6d2e876 100644 --- a/php/12_sort/mergeSort.php +++ b/php/12_sort/mergeSort.php @@ -1,6 +1,6 @@