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

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

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


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

print_r(quick_sort(array(6,1,5,8,7,4,2,3,0)));
function quick_sort($arr) {
//先判断是否需要继续进行
$length = count($arr);
if($length <= 1) {
return $arr;
}
//如果没有返回,说明数组内的元素多于 1 个,需要排序
//选择一个标尺
//选择第一个元素
$base_num = $arr[0];
//遍历 除了标尺外所有元素,按照大小关系放入两个数组内
//初始化两个数组
$left_array = array(); //小于标尺的
$right_array = array(); //大于标尺的
for($i=1; $i<$length; $i++) {
if($base_num > $arr[$i]) {
//放入左边数组
$left_array[] = $arr[$i];
} else {
//放入右边数组
$right_array[] = $arr[$i];
}
}
printf("in[%s] B[%d] L[%s] R[%s]
", join(',', $arr), $base_num, join(',', $left_array), join(',', $right_array));
//再分别对 左边 和 右边 得得数组进行相同的排序处理
//递归调用这个函数,并记录结果
$left_array = quick_sort($left_array);
$right_array = quick_sort($right_array);
//合并左边、标尺、右边
return array_merge($left_array, array($base_num), $right_array);
}
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]
in[1,5,4,2,3,0] B[1] L[0] R[5,4,2,3]
in[5,4,2,3] B[5] L[4,2,3] R[]
in[4,2,3] B[4] L[2,3] R[]
in[2,3] B[2] L[] R[3]
in[8,7] B[8] L[7] R[]
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!