冒泡排序
$test=[5,6,11,8,10,2,3,123,5,-1];
$len=count($test);
while (true) {
if ($len <= 1) {
break;
}
$i = 0;
while (true) {
if ($i > $len - 2) {
break;
}
if ($test[$i] > $test[$i + 1]) {
$middle = $test[$i];
$test[$i] = $test[$i + 1];
$test[$i + 1] = $middle;
}
$i++;
}
$len--;
}
print_r($test);die;
快速排序
//交换数组元素值
function swapVal(&$test,$low,$high){
$temp=$test[$low];
$test[$low]=$test[$high];
$test[$high]=$temp;
}
function quickSort(&$test,$low,$high)
{
if($low>=$high){
return;
}
//获取基准
$middle=$test[$low];
//记录初始最左最后index
$left=$low;
$right=$high;
//基准放到最后
swapVal($test,$low,$high);
//交换除最后位的所有元素,直到最后一位
while(true){
while(($low<$high)&&($middle>=$test[$low])) $low++;
while(($low<$high)&&($middle<=$test[$high])) $high--;
if($low<$high){
swapVal($test,$low,$high);
}else{
break;
}
}
//基准回到中间
swapVal($test,$low,$right);
//分别对左右两个边的序列继续快排
quickSort($test,$left,$low-1);
quickSort($test,$low+1,$right);
}
$test=[5,6,11,8,10,2,3,123,5,-1];
quickSort($test,0,count($test)-1);
print_r($test);die;