-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.php
More file actions
56 lines (46 loc) · 956 Bytes
/
mergeSort.php
File metadata and controls
56 lines (46 loc) · 956 Bytes
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
<?php
/**
* 归并排序
*
* @param array $arr
* @return unknown|array
*/
function mergeSort($arr)
{
if (count($arr) <= 1) {
return $arr;
}
// 拆分数组
$left = array_slice($arr, 0, (int) (count($arr) / 2));
$right = array_slice($arr, (int) (count($arr) / 2));
$left = mergeSort($left);
$right = mergeSort($right);
$output = merge($left, $right);
return $output;
}
function merge($left, $right)
{
$result = array();
while (count($left) > 0 && count($right) > 0) {
if ($left[0] <= $right[0]) {
array_push($result, array_shift($left));
} else {
array_push($result, array_shift($right));
}
}
array_splice($result, count($result), 0, $left);
array_splice($result, count($result), 0, $right);
return $result;
}
$arr = array(
6,
3,
2,
7,
1,
5,
8,
4
);
$output = mergeSort($arr);
print_r($output);