$a =array (' 3 ', ' 8 ', ' 1 ', ' 4 ', ' One ', ' 7 ');p Rint_r ($a), $len = count ($a);//from Small to large for ($i =1; $i < $len; $i + +) {for ($j = $len-1; $j >= $i; $j-) if ($a [$j]< $a [$j-1]) {//If it is from large to small, if the judgment here is changed to if ($b [$j]> $b [$j-1]) $x = $a [$j]; $a [$j]= $a [$j-1]; $a [$j -1]= $x;}} Print_r ($a); j//another method from small to large $b=array (' 4 ', ' 3 ', ' 8 ', ' 9 ', ' 2 ', ' 1 '), $len =count ($b); for ($k =1; $k < $len; $k + +) {for ($j =$ Len-1, $i =0, $i < $len-$k, $i + +, $j-) if ($b [$j]< $b [$j-1]) {///if it is from large to small, as long as the judgment here is changed to if ($b [$j]> $b [$j-1]) $tmp = $b [$j]; $b [$j]= $b [$j-1]; $b [$j -1]= $tmp;} Print_r ($b); echo "";} The following performance is more efficient function Maopao ($arr) {$len = count ($arr); for ($i =1; $i < $len; $i + +)//up to n-1 sequencing {$flag = false; The interchange flag should be false for ($j = $len-1; $j >= $i; $j-) {if ($arr-$j]< $arr [$j-1])//Exchange Record {///if it is from large to small, as long as the judgment here is changed to if ($arr [ $j]> $arr [$j-1]) can be $x = $arr [$j]; $arr [$j]= $arr [$j-1]; $arr [$j -1]= $x; $flag = true;//swapped, so the swap flag is set to True} if (! $flag)//The current order does not occur, the early termination algorithm return $arr; }} $shuz = Array (' 2 ', ' 4 ', ' 1 ', ' 8 ', ' 5 '); $BB = Maopao ($shuz);p rint_r ($BB);//Quick Sort function KuaiSU ($arr) {$len = count ($arr); if ($len <= 1) {return $arr; } $key = $arr [0]; $left _arr = Array (); $right _arr = Array (); for ($i =1; $i < $len; $i + +) {if ($arr [$i] <= $key) {$left _arr[] = $arr [$i]; }else{$right _arr[] = $arr [$i]; }} $left _arr = Kuaisu ($left _arr); $right _arr = Kuaisu ($right _arr); Return Array_merge ($left _arr, Array ($key), $right _arr);} $arr = Array (23,98,54,2,9,62,34);p Rint_r (Kuaisu ($arr));
Php bubble Sort and Quick sort instance detailed