1. 程式人生 > >幾種常見排序方法

幾種常見排序方法

冒泡

function bubble($data){
    $size = count($data);
    for($i=0;$i<$size;$i++){
        for($j=$i+1;$j<$size;$j++){
            if($data[$i]<$data[$j]){
                $tmp = $data[$j];
                $data[$j] = $data[$i];
                $data[$i] = $tmp;
            }
        }
    }
    return
$data; }

快排

function quicksort($data){
    $size = count($data);
    $k = $data[0];
    $x = array();
    $y = array();
    if($size>1){
        for($i=1;$i<$size;$i++){
            if($data[$i]<=$k){
                $x[] = $data[$i];
            }else{
                $y[] = $data[$i];
            }
        }
        $x
= quicksort($x); $y = quicksort($y); return array_merge($x, array($k), $y); }else{ return $data; } }

二分查詢(效率高但必須是排好序的數列)

function binary_search($num, $data){
    $size = count($data);
    $low = 0;
    $height = $size - 1;

    while($height>=$low){
        $mid
= floor(($low + $height) / 2); if($num == $data[$mid]){ return $mid; }elseif($num > $data[$mid]){ $low = $mid + 1; }elseif($num < $data[$mid]){ $height = $mid -1; } } }

斐波那契數列

//遞迴
function recursion($num){
    if($num<=2)return 1;
    return recursion($num - 1) + recursion($num - 2);
}
//迴圈
function circle($num){
    $x = 0;
    $y = 1;
    $z = 0;
    if($num==1)return 1;
    for($i=2;$i<=$num;$i++){
        $z = $x + $y;
        $x = $y;
        $y = $z;
    }
    return $z;
}