Home > Backend Development > PHP Problem > How to implement common sorting in php

How to implement common sorting in php

醉折花枝作酒筹
Release: 2023-03-10 10:52:02
forward
2065 people have browsed it

This article will introduce to you how to implement common sorting in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to implement common sorting in php

$arr = [4,5,3,2,1,9,8,6,7];
Copy after login

Bubble sort

function maopao($arr)
{
    $len = count($arr);
    for ($i=1; $i <$len ; $i++) { 
        # code...
        for ($k=0; $k <($len-$i) ; $k++) { 
            # code...
            if ($arr[$k]>$arr[$k+1]) {
                # code...
                $v_k = $arr[$k];
                $arr[$k]=$arr[$k+1];
                $arr[$k+1]=$v_k;    
            }
        }
    }
    return $arr;
}
Copy after login

Quick sort

function kuaisu($arr)
{
    $len = count($arr);
    if ($len<=1) {
        # code...
        return $arr;
    }
    //选择基准元素
    $a = $arr[0];
    $left = $right = [];
    //循环
    for ($i=1; $i < $len; $i++) { 
        # code...
        if ($arr[$i]<$a) {
            # code...
            $left[]=$arr[$i];
        }else{
            $right[]=$arr[$i];
        }
    }
    $left = kuaisu($left);
    $right = kuaisu($right);
    return array_merge($left,[$a],$right);
}
Copy after login

Insertion sort

function insertSort($arr)
{
    $len = count($arr);
    for ($i=1; $i < $len; $i++) { 
        # code...
        $tmp = $arr[$i];
        for ($j=$i-1; $j >=0 ; $j--) { 
            # code...
            if ($tmp<$arr[$j]) {
                    # code...
                $arr[$j+1]=$arr[$j];
                $arr[$j]=$tmp;    
            }else{
                break;
            }    
        }
    }
    return $arr;
    }
Copy after login

Selection sort

function selectSort($arr)
{
    $len = count($arr);

    for ($i=0; $i < $len; $i++) { 
        # code...
        $p=$i;

        for ($j=$i+1; $j < $len; $j++) { 
            # code...
            if ($arr[$p]>$arr[$j]) {
                # code...
                $p=$j;
            }

        }

        $tmp = $arr[$p];
        $arr[$p]=$arr[$i];
        $arr[$i]=$tmp;

    }

    return $arr;
}
Copy after login

Recommended learning: php video tutorial

The above is the detailed content of How to implement common sorting in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template