归并排序(php实现)

<?php 

function mergeSort(&$arr){

	$len = count($arr);

	

	msort($arr,0,$len-1);

}



function msort(&$arr,$low,$high){

	if($low<$high){

		$mid = floor(($low+$high)/2);

		msort($arr, $low, $mid);

		msort($arr,$mid+1,$high);

		mergeArray($arr,$low,$mid,$high);

	}

}



function mergeArray(&$arr,$low,$mid,$high){

	$i = $low;

	$j = $mid+1;

	

	while($i<=$mid && $j<=$high){

		if($arr[$i]<$arr[$j]){

			$tmp[] = $arr[$i++];

		}else{

			$tmp[] = $arr[$j++];

		}

		

	}

	

	while($i<=$mid){

		$tmp[] = $arr[$i++];

	}

	while($j<=$high){

		$tmp[] = $arr[$j++];

	}

	$len = count($tmp);

	for($k=0;$k<$len;$k++){

		$arr[$low+$k] = $tmp[$k];

	}

}



$arr = array(1,2,3,7,9,0,4,6,5,1);

mergeSort($arr);

print_r($arr);

?>

  

你可能感兴趣的:(归并排序)