【PHP】排序算法
如果有兴趣的话,请随时添加。
我写一些用于确认的测试代码
然后与asort函数的结果进行比较
如果能够查看性能也不错
冒泡排序 bō
function bable_sort($para){
$cnt = count($para);
for($i=0;$i<$cnt-1;$i++){
for($j=$i+1;$j<$cnt;$j++){
if($para[$i]>$para[$j]){
$tmp = $para[$i];
$para[$i] = $para[$j];
$para[$j] = $tmp;
}
}
}
return $para;
}
快速排序 sù
中途
请参考以下链接中的PHP快速排序算法实现:
https://github.com/Khanashima/algorithm/blob/master/src/sort/quickSort.php
function quickSort(&$list, $first, $last) {
echo PHP_EOL;
echo 'first:'.$first,' last:'.$last,PHP_EOL;
$firstPointer = $first;
$lastPointer = $last;
//枢軸値を決める。配列の中央値
$centerValue = $list[intVal(($firstPointer + $lastPointer) / 2)];
//$centerValue = $list[$firstPointer];
echo 'centerValue:'.$centerValue,PHP_EOL;
//並び替えができなくなるまで
do {
//枢軸よりも左側で値が小さい場合はポインターは進める
while ($list[$firstPointer] < $centerValue) {
$firstPointer++;
}
//枢軸よりも右側で値が大きい場合はポインターを減らす
while ($list[$lastPointer] > $centerValue) {
$lastPointer--;
}
//この操作で左側と右側の値を交換する場所は特定
if ($firstPointer <= $lastPointer) {
echo 'firstPointer:'.$firstPointer,'→',$list[$firstPointer],' ','lastPointer:'.$lastPointer,'→',$list[$lastPointer],PHP_EOL;
//ポインターが逆転していない時は交換可能
$tmp = $list[$lastPointer];
$list[$lastPointer] = $list[$firstPointer];
$list[$firstPointer] = $tmp;
//ポインタを進めて分割する位置を指定
$firstPointer++;
$lastPointer--;
}
} while ($firstPointer <= $lastPointer);
if ($first < $lastPointer) {
//左側が比較可能の時
quickSort($list, $first, $lastPointer);
}
if ($firstPointer < $last) {
//右側が比較可能時
quickSort($list, $firstPointer, $last);
}
}
$list = [3,5,2,4,9,11,8];
quickSort($list,0, count($list)-1);
var_dump($list);