<?php
$arr = array(9,1,5,8,3,7,4,6,7);
foreach ($arr as $key => $value) {
echo $value."\n";
}
//一次归并算法
function merge(&$arr,$s,$m,$e){
$i=$s;
$j=$m+1;
$k=$s;
$arr1 = Array();
while($i<=$m && $j<=$e){
if ($arr[$i]<=$arr[$j]) {
$arr1[$k++]=$arr[$i++];
}else{
$arr1[$k++]=$arr[$j++];
}
}
while($i<=$m){
$arr1[$k++]=$arr[$i++];
}
while($j<=$e){
$arr1[$k++]=$arr[$j++];
}
for($i=$s; $i<=$e; $i++){
$arr[$i] = $arr1[$i];
}
}
//一趟归并算法
function mergeOne(&$arr,$n,$h){
$i=0;
while($i<=$n-(2*$h)+1){
merge($arr,$i,$i+$h-1,$i+($h*2)-1);
$i+=2*$h;
}
if($i<=$n-$h+1){
merge($arr,$i,$i+$h-1,$n);
}
}
//非递归
function mergeSort(&$arr,$n){
$h=1;
while($h<$n+1){
mergeOne($arr,$n,$h);
$h=$h*2;
}
}
//递归
function mergeSort2(&$arr,$s,$e){
if($s < $e){
$middle = floor(($s+$e)/2);
mergeSort2($arr,$s,$middle);
mergeSort2($arr,$middle+1,$e);
merge($arr,$s,$middle,$e);
}
}
//mergeSort($arr,count($arr)-1);
mergeSort2($arr,0,count($arr)-1);
echo "<br>";
foreach ($arr as $key => $value) {
echo $value."\n";
}