Home >Backend Development >PHP Tutorial > 快速排序,该怎么处理

快速排序,该怎么处理

WBOY
WBOYOriginal
2016-06-13 13:41:55990browse

快速排序
function quicksort($arr,$lo0,$hi0) {
$lo = $lo0;
$hi = $hi0;
$flag = true;
$tmp = 0;

if($lo>$hi) {
return ;

}

while ($lo!=$hi) {

if($arr[$lo]>$arr[$hi]) {

$tmp = $arr[$lo];
$arr[$lo] = $arr[$hi];
$arr[$hi] = $tmp;

$flag = ($flag==true)?false:true;

}

if($flag) {
$lo++;
}else {
$hi--;
}

}

$lo--;
$hi++;

quicksort($arr,$lo0,$lo);
quicksort($arr,$hi,$hi0);
}

$arr = array(5,4,2,6,8,1,10,9);
quicksort($arr,0,count($arr)-1);

for($i=0;$i
echo "arr[$i]=".$arr[$i]."
";

}
上面红色部分怎么无法判断,郁闷。。

------解决方案--------------------
不是 if($arr[$lo]>$arr[$hi]) { 判断无效
而是交换数组元素的动作没有保存

function quicksort(&$arr,$lo0,$hi0) {
传引用即可
------解决方案--------------------
函数没有返回值,你要这样

function quicksort(&$arr,$lo0,$hi0)// &引用

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