forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeSort.php
66 lines (46 loc) · 1.08 KB
/
mergeSort.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
$arr = [4, 5, 6, 1, 3, 2];
$length = count($arr);
$p = 0;
$r = $length - 1;
$result = $this->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;
$copyArr = $left;
if ($j < $rightLength) {
$start = $j;
$end = $rightLength;
$copyArr = $right;
}
for (; $start < $end; $start++) {
$tmp[] = $copyArr[$start];
}
return $tmp;
}