A sort of bubble sort in PHP

Source: Internet
Author: User

Bubble sorting is relatively straightforward. As many companies interview pen questions often appear, require handwritten this sorting algorithm. Double-layer cycle, continuous and the subsequent comparison, if greater than the subsequent, the order can be reversed.

Demo effect

The code is as follows:

<?PHPfunctionBubblesort ($array=Array()){    $length=Count($array);//Get Array length     for($i= 0;$i<$length;$i++)    {        #Loop Array         for($j=$i+1;$j<$length;$j++)        {            #itself compared to the people behind itself            if($array[$i]>$array[$j])            {                //The order is not reversed to implement bubbling//two number exchange value                $tmp=$array[$i];//give the first value to a temporary variable                $array[$i]=$array[$j];//give the value of J to I                $array[$j]=$tmp;//give the TMP to J .            }        }    }    return $array;//returns an array}?>

The calling code is as follows:

<? PHP $array=array(10,9,8,7,6,5,4,3,2,1); $result=bubblesort ($array); Var_dump ($result);? >

Effect

A sort of bubble sort in PHP

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.