PHP快速排序算法(非递归)实现
2018-07-20 来源:open-open
quicksort.php ~ 1KB
<?php
$i = 100;
while($i > 0){
if($i > 30){
$test[] = mt_rand($i - 30, $i--);
}else{
$test[] = mt_rand(1, $i--);
}
}
//shuffle($test);
echo count($test), "\n";
//sort($test);
echo implode(", ", $test), "\n\n";
$t1 = microtime(true);
quicksort($test);
echo implode(", ", $test), "\n\n";
echo microtime(true) - $t1, "<br>\n";
function quicksort(array &$sort){
$end = count($sort);
if(--$end < 1){
return;
}
$beg = 0;
$stack = array();
while(true){
$i = $beg;
$l = $end;
$o = $sort[
$x = mt_rand($i, $l)
];
while($i < $l){
// 左边大于的
if($sort[$i] > $o){
while($i < $l){
// 右边小于等于的
if($sort[$l] <= $o){
$tmp = $sort[$i];
$sort[$i] = $sort[$l];
$sort[$l] = $tmp;
$i++; $l--;
continue 2;
}
$l--;
}
goto re;
}
$i++;
}
if($sort[$i] < $o){
$sort[$x] = $sort[$i];
$sort[$i] = $o;
}
// echo $i, ", ", $l, "; ", $beg, ", ", $end, "\n";
re:
// 保存右边
if($i < $end){
$stack[] = $i;
$stack[] = $end;
}
if(--$i > $beg){
$end = $i; // 继续左边
}elseif($stack){
// 返回继续右边
$end = array_pop($stack);
$beg = array_pop($stack);
}else{
break;
}
}
}
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:超简单的php缓存类
下一篇:iOS判断手机是否开启麦克风
最新资讯
热门推荐