$a =array (' 3 ', ' 8 ', ' 1 ', ' 4 ', ' 11 ', ' 7 ');
Print_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, just change the judgment here to if ($b [$j]> $b [$j-1]).
$x = $a [$j];
$a [$j]= $a [$j-1];
$a [$j -1]= $x;
}
}
Print_r ($a); j
Another approach 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, just change the judgment here 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 implementation is more efficient
function Maopao ($arr)
{
$len = count ($arr);
for ($i =1; $i < $len; $i + +)//up to n-1 sequencing
{
$flag =false; Before this sequencing begins, the swap 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, just change the judgment here to if ($arr [$j]> $arr [$j-1]).
$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 interchange, early termination algorithm
Return$arr;
}
}
$shuz = Array (' 2 ', ' 4 ', ' 1 ', ' 8 ', ' 5 ');
$BB = Maopao ($shuz);
Print_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);
Returnarray_merge ($left _arr, Array ($key), $right _arr);
}
$arr = Array (23,98,54,2,9,62,34);
Print_r (Kuaisu ($arr));
Php Bubble Sort Quick Sort