-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergesort.php
61 lines (54 loc) · 1.29 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
<?php
$swap=0;
function MergeSort($item)
{
if (count($item)<=1) return $item;
else
{
$left= array();
$right=array();
$middle = (int) ( count($item)/2 );
$left=array_slice($item,0,$middle);
$right= array_slice($item,$middle);
$left=MergeSort($left);
$right=MergeSort($right);
return merge($left,$right);
}
}
function merge($left,$right)
{
$result = array();
while(count($left)>0||count($right)>0)
{
if(count($left)>0 && count($right)>0)
{
if ($left[0]>$right[0])
++$GLOBALS["swap"];
if ($left[0]<=$right[0]) {
$result[]=array_shift($left);
}
else
{
$result[]=array_shift($right);
// $GLOBALS["swap"]++;
}
}
elseif (count($left) > 0)
{
$result[] = array_shift($left);
// $GLOBALS["swap"]++;
}
elseif (count($right) > 0)
{
$result[] = array_shift($right);
// $GLOBALS["swap"]++;
}
}
print_r($result);
return $result;
}
$data=array(7,5,3,1);
$data=MergeSort($data);
print_r($data);
print_r($GLOBALS["swap"]);
?>