Home > Article > Backend Development > How to implement common sorting in php
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.
$arr = [4,5,3,2,1,9,8,6,7];
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; }
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); }
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; }
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; }
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!