Php bubble sorting solution

Source: Internet
Author: User
Php bubble sorting searches for php bubble sorting. I do not know that the second layer of the loop is decreasing on the Internet, which is not in line with my habits. since it is bubble sorting, it must be from bottom up, so I simply wrote a share! & Lt ;? Php & nbsp; $ ar & nbsp; = & nbsp; array (, 24); bub php bubble sorting
After searching for ha php bubble sorting, I did not know that the second layer of the loop is decreasing, which is not in line with my habits. since it is bubble, it must be from bottom up, so I simply wrote a share!


  $ar = array(1,3,2,8,3,5,6,10,13,27,24);
bubble_sort($ar);
print_r($ar);
 function bubble_sort(&$ar)
{
   $ar_count = count($ar);
   $temp = null;
   for($i= 0 ; $i < $ar_count; $i ++)
   {
      for($j = 0 ; $j < $ar_count - $i - 1; $j++)
      {
          if($ar[$j] > $ar[$j+1])
          {
              $temp = $ar[$j];
              $ar[$j] = $ar[$j+1];
              $ar[$j+1] = $temp;
          }
      }
   }
}
Php bubble sorting
------ Solution --------------------
$ Ar = array (24, 1, 3, 2, 8, 3, 5, 6, 10, 13, 27 );
Bubble_sort ($ ar );

Function bubble_sort (& $ ar)
{
$ Ar_count = count ($ ar );
$ Temp = null;
For ($ I = 0; $ I <$ ar_count; $ I ++)
{
For ($ j = 0; $ j <$ ar_count-$ I-1; $ j ++)
{
If ($ ar [$ j]> $ ar [$ j + 1])
{
$ Temp = $ ar [$ j];
$ Ar [$ j] = $ ar [$ j + 1];
$ Ar [$ j + 1] = $ temp;
}
}
Echo join (',', $ ar), PHP_EOL; // observe the output.
}
}
1, 3, 2, 8, 3, 5, 6, 10, 13, 24, 27
The sorting of, and 27 has ended.
Starting from, and 27, the following are all invalid labor.
1, 2, 3, 5, 6, 8, 10, 13, 24, 27
1, 2, 3, 5, 6, 8, 10, 13, 24, 27
1, 2, 3, 5, 6, 8, 10, 13, 24, 27
1, 2, 3, 5, 6, 8, 10, 13, 24, 27
1, 2, 3, 5, 6, 8, 10, 13, 24, 27
1, 2, 3, 5, 6, 8, 10, 13, 24, 27
1, 2, 3, 5, 6, 8, 10, 13, 24, 27
1, 2, 3, 5, 6, 8, 10, 13, 24, 27

Great room for optimization

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.