php4中排序算法

1.冒泡排序

//排序方式【desc:倒叙,asc:正序】
$type = 'desc';
$arr = array(1,2,3,8,6,0,9,100,500,25,10);
for($i = 0; $i < count($arr); $i++)
{
    for($j = $i + 1; $j < count($arr); $j ++)
    {
         if(($arr[$j] > $arr[$i] && $type == 'desc') || ($arr[$j] < $arr[$i] && $type == 'asc'))
         list($arr[$i], $arr[$j]) = array($arr[$j],$arr[$i]);
    }
}
print_r($arr);

运行结果:

Array ( [0] => 500 [1] => 100 [2] => 25 [3] => 10 [4] => 9 [5] => 8 [6] => 6 [7] => 3 [8] => 2 [9] => 1 [10] => 0 ) 

2.快速排序

function sortArr($arr, $type)
{
     if(($count = count($arr)) <= 1 ) return $arr;
     $base = $arr[0];
     $left = $right = [];
     for ($i = 0; $i < count($arr); $i ++)
     {
         if(($arr[$i] <= $base && $type == 'asc') || ($arr[$i] > $base && $type == 'desc'))
         {
             $left[] = $arr[$i];
         }
         else
         {
            $right[] = $arr[$i];
         }
     }
     $left = sortArr($left,$type);
     $right = sortArr($right,$type);
     return array_merge($left, array($base), $right);
}
$arr = [1,2,3,8,6,0,9,100,500,25,10];
$type = 'desc';
sortArr($arr, $type);

3.插入排序

$type = 'desc';
//快速排序
$arr = [1,2,3,8,6,0,9,100,500,25,10];
for($i = 1; $i < count($arr); $i++) {
     $k = $i;
     while($k > 0) {
       if(($arr[$k-1] > $arr[$k] && $type == 'asc') || ($arr[$k-1] < $arr[$k] && $type == 'desc'))
            list($arr[$k], $arr[$k-1]) = array($arr[$k-1], $arr[$k]);
       $k--;
     }
}
var_dump($arr);

运行结果:

array (size=11)
  0 => int 500
  1 => int 100
  2 => int 25
  3 => int 10
  4 => int 9
  5 => int 8
  6 => int 6
  7 => int 3
  8 => int 2
  9 => int 1
  10 => int 0

4.选择排序

        $type = 'desc';
        //快速排序
        $arr = [1,2,3,8,6,0,9,100,500,25,10];
        for($i = 0; $i < count($arr); $i++) {
            $index = $i;
            $tmp = $arr[$i];
            for($j = $i + 1; $j < count($arr); $j++)
            {
                if(($tmp < $arr[$j] && $type == 'desc') || ($tmp > $arr[$j] && $type == 'asc'))
                {
                    $index = $j;
                    $tmp = $arr[$j];
                }
            }
            if($index != $i) list($arr[$index], $arr[$i]) = array($arr[$i], $arr[$index]);
        }
        var_dump($arr);

运行结果:

array (size=11)
  0 => int 500
  1 => int 100
  2 => int 25
  3 => int 10
  4 => int 9
  5 => int 8
  6 => int 6
  7 => int 3
  8 => int 2
  9 => int 1
  10 => int 0
添加新评论