Home >Backend Development >PHP Tutorial >Data structure (8) Merge sort

Data structure (8) Merge sort

WBOY
WBOYOriginal
2016-08-08 09:32:111115browse
Merge sort algorithm implementation:
<?php
	
	//归并排序

	function all_array_merge($arrA,$arrB){
		$arrC=array();
	
		$i=$j=$k=0;
		$arrA_length=count($arrA);
		$arrB_length=count($arrB);
		while($i<$arrA_length && $j<$arrB_length){
			if($arrA[$i]<$arrB[$j]){
				$arrC[]=$arrA[$i++];
			}else{
				$arrC[]=$arrB[$j++];
			}
		}
		while($i<$arrA_length){
			$arrC[]=$arrA[$i++];
		}
		while($j<$arrB_length){
			$arrC[]=$arrB[$j++];
		}

		return $arrC;
	}

	function array_merge_sort($array){
		$length=count($array);
		if($length<=1){
			return $array;
		}
		$mid=intval($length/2);//取数组中间元素的坐标
		$array_left=array_slice($array,0,$mid);//拆分元素0-mid折部分给左边$array_left
		$array_right=array_slice($array,$mid);//拆分数组mid-$length-1这部分给右边$array_right
		$array_left=array_merge_sort($array_left);//左边拆分完后开始递归合并
		$array_right=array_merge_sort($array_right);//右边拆分完后开始递归
		$result=all_array_merge($array_left,$array_right);//合并两个数组,递归合并)
		return $result;
	}

	$arr=array(456,35,77,356,33,98,11,44,82);
	$res=array_merge_sort($arr);
	foreach($res as $key => $value){
		echo "key: ".$key."    value: ".$value."<br/>";
	}
?>

The above introduces the data structure (8) merge sorting, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn