Skip to content

Commit 5d14066

Browse files
committed
php 12_merge_sort
1 parent 91826a7 commit 5d14066

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

php/12_sort/mergeSort.php

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
3+
$arr = [1, 5, 8, 6, 7, 9];
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+
$start = $i;
50+
$end = $leftLength;
51+
52+
if ($j < $rightLength) {
53+
$start = $j;
54+
$end = $rightLength;
55+
}
56+
57+
for (; $start < $end; $start++) {
58+
$tmp[] = $right[$start];
59+
}
60+
61+
return $tmp;
62+
63+
}

0 commit comments

Comments
 (0)