1, bubble sort:

Pairwise, you don’t need to compare the last element for each cycle, 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;
}

Copy the code

2, selection sort:

Pick one as the base, compare the rest to this, and switch 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;
}

Copy the code

3. Quicksort:

The idea is to take a ruler value, divide it into left and right arrays, and compare them

function kuaisuSort ($list)
{
    $len = count($list);
    if ($len< =1) {// Recursive exit
        return $list;
    }
    $base = $list[0];// Select a comparison value
    $leftList = $rightList = [];
    for ($i = 1; $i < $len; $i{+ +)if ($base > $list[$i]) {
            $leftList[] = $list[$i];
        } else {
            $rightList[] = $list[$i]; }}// Recursively process the left and right arrays respectively
    $leftList = kuaisuSort($leftList);
    $rightList = kuaisuSort($rightList);
    return array_merge($leftList[$base].$rightList);
}

Copy the code

4, insert sort:

Assuming everything is sorted, we’re going to insert the NTH term into the order

function charuSort ($list)
{
    $len = count($list);
    for ($i = 1; $i < $len; $i{+ +)$tmp = $list[$i];// Get the contrast element
        for ($j = $i - 1; $j > 0; $j-) {if ($list[$j] > $tmp) {
                $list[$j + 1] = $list[$j];
                $list[$j] = $tmp;
            } else {
                break; }}}return $list;
}

Copy the code

The above content hopes to help you, more free PHP factory PDF, PHP advanced architecture video materials, PHP wonderful good article can be wechat search concerns: PHP open source community

2021 Jinsanyin four big factory interview real questions collection, must see!

Four years of PHP technical articles collation collection – PHP framework

A collection of four years’ worth of PHP technical articles – Microservices Architecture

Distributed Architecture is a four-year collection of PHP technical articles

Four years of PHP technical essays – High Concurrency scenarios

Four years of elite PHP technical article collation collection – database