请问一个快速排序法的有关问题

WBOY
Release: 2016-06-13 12:10:06
Original
1049 people have browsed it

请教一个快速排序法的问题


------解决思路----------------------
每次执行都是函数体内的局部变量,除非是静态或全局变量才会改变
------解决思路----------------------
这样看的清楚点

print_r(quick_sort(array(6,1,5,8,7,4,2,3,0)));<br />function quick_sort($arr) {<br />	//先判断是否需要继续进行<br />	$length = count($arr);<br />	if($length <= 1) {<br />		return $arr;<br />	}<br />	//如果没有返回,说明数组内的元素多于 1 个,需要排序<br />	//选择一个标尺<br />	//选择第一个元素<br />	$base_num = $arr[0];<br />	//遍历 除了标尺外所有元素,按照大小关系放入两个数组内<br />	//初始化两个数组<br />	$left_array = array(); //小于标尺的<br />	$right_array = array(); //大于标尺的<br />	for($i=1; $i<$length; $i++) {<br />		if($base_num > $arr[$i]) {<br />			//放入左边数组<br />			$left_array[] = $arr[$i];<br />		} else {<br />			//放入右边数组<br />			$right_array[] = $arr[$i];<br />		}<br />	}<br />printf("in[%s] B[%d] L[%s] R[%s]<br>", join(',', $arr), $base_num, join(',', $left_array), join(',', $right_array));<br />	//再分别对 左边 和 右边 得得数组进行相同的排序处理<br />	//递归调用这个函数,并记录结果<br />	$left_array = quick_sort($left_array);<br />	$right_array = quick_sort($right_array);<br />	//合并左边、标尺、右边<br />	return array_merge($left_array, array($base_num), $right_array);<br />}
Copy after login
in[6,1,5,8,7,4,2,3,0] B[6] L[1,5,4,2,3,0] R[8,7]<br />in[1,5,4,2,3,0] B[1] L[0] R[5,4,2,3]<br />in[5,4,2,3] B[5] L[4,2,3] R[]<br />in[4,2,3] B[4] L[2,3] R[]<br />in[2,3] B[2] L[] R[3]<br />in[8,7] B[8] L[7] R[]<br />Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 ) 
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template