Skip to content

Commit 9d64c82

Browse files
Merge pull request #104 from iyoungm/master
php_12_sort_mergeSort
2 parents d8d7806 + bfb3dd5 commit 9d64c82

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

php/12_sort/mergeSort.php

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?php
2+
3+
$arr = [4, 5, 6, 1, 3, 2];
4+
$length = count($arr);
5+
6+
$p = 0;
7+
$r = $length - 1;
8+
9+
$result = $this->mergeSort($arr, $p, $r);
10+
11+
var_dump($result);
12+
13+
14+
//递归调用,分解数组
15+
function mergeSort(array $arr, $p, $r)
16+
{
17+
if ($p >= $r) {
18+
return [$arr[$r]];
19+
}
20+
$q = (int)(($p + $r) / 2);
21+
22+
$left = $this->mergeSort($arr, $p, $q);
23+
$right = $this->mergeSort($arr, $q + 1, $r);
24+
return $this->merge($left, $right);
25+
}
26+
27+
//合并
28+
function merge(array $left, array $right)
29+
{
30+
$tmp = [];
31+
32+
$i = 0;
33+
34+
$j = 0;
35+
36+
$leftLength = count($left);
37+
38+
$rightLength = count($right);
39+
40+
do {
41+
if ($left[$i] <= $right[$j]) {
42+
$tmp[] = $left[$i++];
43+
} else {
44+
$tmp[] = $right[$j++];
45+
}
46+
47+
} while ($i < $leftLength && $j < $rightLength);
48+
49+
50+
$start = $i;
51+
$end = $leftLength;
52+
$copyArr = $left;
53+
54+
if ($j < $rightLength) {
55+
$start = $j;
56+
$end = $rightLength;
57+
$copyArr = $right;
58+
}
59+
60+
for (; $start < $end; $start++) {
61+
$tmp[] = $copyArr[$start];
62+
}
63+
64+
return $tmp;
65+
66+
}

0 commit comments

Comments
 (0)