| 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