Achieve some common sorting algorithm PHP

1, bubble sort:

Pairwise, each cycle round will not need to compare the last element, because the last element is already the largest or smallest.

function maopaoSort ($list)
{
    $len = count($list);
    for ($i = 0; $i < $len - 1; $i++) {
        for ($j = 0; $j < $len - $i - 1; $j++) {
            if ($list[$j] > $list[$j + 1]) {
                $tmp = $list[$j];
                $list[$j] = $list[$j + 1];
                $list[$j + 1] = $tmp;
            }
        }
    }
    return $list;
}

2. Select Sort:

Selected as a fundamental value, and the rest of this comparison, then exchange places.

function xuanzeSort ($list)
{
    $len = count($list);
    for ($i = 0; $i < $len - 1; $i++) {
        $pos = $i;
        for ($j = $i + 1; $j < $len; $j++) {
            if ($list[$pos] > $list[$j]) {
                $pos = $j;
            }
        }
        if ($pos != $i) {
            $tmp = $list[$pos];
            $list[$pos] = $list[$i];
            $list[$i] = $tmp;
        }
    }
    return $list;
}

3, quick sort:

Principle is to come up with a scale value, and then divided into left and right two arrays, respectively Comparison

function kuaisuSort ($list)
{
    len $ = COUNT ( $ List );
     IF ( $ len <=. 1) { // recursive outlet 
        return  $ List ;
    }
    Base $ = $ List [0]; // to select a comparison value 
    $ leftList = $ rightList = [];
     for ( $ I =. 1; $ I < $ len ; $ I ++ ) {
         IF ( $ Base > $ List [ $ I ]) {
             $ leftList [] = $ List [ $ I ];
        } else {
            $rightList[] = $list[$i];
        }
    }
    // recursive left and right sides, respectively, and then the processing array 
    $ leftList = kuaisuSort ( $ leftList );
     $ rightList = kuaisuSort ( $ rightList );
     return  The array_merge ( $ leftList , [ $ Base ], $ rightList );
}

4, insertion sort:

Suppose the number of the foregoing are in good order, the number n should be inserted into a first ordered in

function charuSort ($list)
{
    $len = count($list);
    for ($i = 1; $i < $len; $i++) {
        $tmp = $list[$i];//获取对比元素
        for ($j = $i - 1; $j > 0; $j--) {
            if ($list[$j] > $tmp) {
                $list[$j + 1] = $list[$j];
                $list[$j] = $tmp;
            } else {
                break;
            }
        }
    }
    return $list;
}

 

Guess you like

Origin www.cnblogs.com/deverz/p/11082336.html