Php Bubble Sort Quick Sort

Source: Internet
Author: User

$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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.