PHP Bubble sort

Source: Internet
Author: User

1234567891011121314151617181920 /** * 冒泡排序 */$list = Array(6,8,7,2,3,4,1);echo "排序前";print_r($list);function mao($arr){    for($i=1,$len=count($arr);$i<$len;++$i){ // 外层循环 数组个数-1     也就是找几次最大数,找出数组个数-1个就可以了        for($k=0,$klen=$len-$i;$k<$klen;++$k){ // 内层循环,比较两个数组元素   第一次循环找出最大的那个             if($arr[$k]>$arr[$k+1]){                $temp = $arr[$k];                $arr[$k] = $arr[$k+1];                $arr[$k+1] = $temp;            }        }    }    return $arr;}echo "<br/>排序后";print_r(mao($list));

In the process of doing bubbles, the idea has been in the minds of others, in the process of Baidu, see another way, feel good also written over:

123456789101112131415161718 $list = Array(6,8,7,2,3,4,1);echo "排序前";print_r($list);function mao($arr){    for($i=0,$len=count($arr)-1;$i<$len;++$i){ // 外层循环 进行第一层遍历        // 内层循环,在外层的基础上加一,来控制两个元素的比较        for($k=$i+1;$k<=$len;++$k){             if($arr[$i]>$arr[$k]){                $temp = $arr[$i];                $arr[$i] = $arr[$k];                $arr[$k] = $temp;            }        }    }    return $arr;}echo "<br/>排序后";print_r(mao($list));

  

PHP Bubble 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.