-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.php
More file actions
39 lines (36 loc) · 1.21 KB
/
MergeSort.php
File metadata and controls
39 lines (36 loc) · 1.21 KB
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
<?php
class MergeSort
{
public static function sort($a)
{
$len = count($a);
$mid = $len / 2;
if ($len > 1) {
// split array into two parts
$leftPart = array_slice($a, 0, $mid);
$rightPart = array_slice($a, $mid, $mid+1);
// split and do merge sort recursively
$leftPart = self::sort($leftPart);
$rightPart = self::sort($rightPart);
// merge two ordered arrays into one
$leftIndex = $rightIndex = 0;
for ($i = 0; $i < $len ; $i++) {
if ($leftIndex == count($leftPart)) {
$a[$i] = $rightPart[$rightIndex];
$rightIndex++;
} elseif ($rightIndex == count($rightPart)) {
$a[$i] = $leftPart[$leftIndex];
$leftIndex++;
} elseif ($leftPart[$leftIndex] > $rightPart[$rightIndex]) {
$a[$i] = $rightPart[$rightIndex];
$rightIndex++;
} else {
$a[$i] = $leftPart[$leftIndex];
$leftIndex++;
}
}
return $a;
}
return $a;
}
}