php写的冒泡排序(降序),别看广告,看疗效。
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$arr = [1,4,8,10,6,2,30]; echo '这是原始数组<br>'; print_r($arr); // echo '<br>'; // $count = count($arr); $x = 1; // for(;$count>1;$count--){ echo '第【'.$x.'】轮比较开始 >> $count=' . $count; for($i=1;$i<$count;$i++){ if($arr[$i]>$arr[$i-1]){ $tmp = $arr[$i]; $arr[$i] = $arr[$i-1]; $arr[$i-1] = $tmp; } echo '<br>'; // print_r($arr); // } echo '<br>'; // $x++; // } |
输出结果:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
这是原始数组 Array ( [0] => 1 [1] => 4 [2] => 8 [3] => 10 [4] => 6 [5] => 2 [6] => 30 ) 第【1】轮比较开始 >> $count=7 Array ( [0] => 4 [1] => 1 [2] => 8 [3] => 10 [4] => 6 [5] => 2 [6] => 30 ) Array ( [0] => 4 [1] => 8 [2] => 1 [3] => 10 [4] => 6 [5] => 2 [6] => 30 ) Array ( [0] => 4 [1] => 8 [2] => 10 [3] => 1 [4] => 6 [5] => 2 [6] => 30 ) Array ( [0] => 4 [1] => 8 [2] => 10 [3] => 6 [4] => 1 [5] => 2 [6] => 30 ) Array ( [0] => 4 [1] => 8 [2] => 10 [3] => 6 [4] => 2 [5] => 1 [6] => 30 ) Array ( [0] => 4 [1] => 8 [2] => 10 [3] => 6 [4] => 2 [5] => 30 [6] => 1 ) 第【2】轮比较开始 >> $count=6 Array ( [0] => 8 [1] => 4 [2] => 10 [3] => 6 [4] => 2 [5] => 30 [6] => 1 ) Array ( [0] => 8 [1] => 10 [2] => 4 [3] => 6 [4] => 2 [5] => 30 [6] => 1 ) Array ( [0] => 8 [1] => 10 [2] => 6 [3] => 4 [4] => 2 [5] => 30 [6] => 1 ) Array ( [0] => 8 [1] => 10 [2] => 6 [3] => 4 [4] => 2 [5] => 30 [6] => 1 ) Array ( [0] => 8 [1] => 10 [2] => 6 [3] => 4 [4] => 30 [5] => 2 [6] => 1 ) 第【3】轮比较开始 >> $count=5 Array ( [0] => 10 [1] => 8 [2] => 6 [3] => 4 [4] => 30 [5] => 2 [6] => 1 ) Array ( [0] => 10 [1] => 8 [2] => 6 [3] => 4 [4] => 30 [5] => 2 [6] => 1 ) Array ( [0] => 10 [1] => 8 [2] => 6 [3] => 4 [4] => 30 [5] => 2 [6] => 1 ) Array ( [0] => 10 [1] => 8 [2] => 6 [3] => 30 [4] => 4 [5] => 2 [6] => 1 ) 第【4】轮比较开始 >> $count=4 Array ( [0] => 10 [1] => 8 [2] => 6 [3] => 30 [4] => 4 [5] => 2 [6] => 1 ) Array ( [0] => 10 [1] => 8 [2] => 6 [3] => 30 [4] => 4 [5] => 2 [6] => 1 ) Array ( [0] => 10 [1] => 8 [2] => 30 [3] => 6 [4] => 4 [5] => 2 [6] => 1 ) 第【5】轮比较开始 >> $count=3 Array ( [0] => 10 [1] => 8 [2] => 30 [3] => 6 [4] => 4 [5] => 2 [6] => 1 ) Array ( [0] => 10 [1] => 30 [2] => 8 [3] => 6 [4] => 4 [5] => 2 [6] => 1 ) 第【6】轮比较开始 >> $count=2 Array ( [0] => 30 [1] => 10 [2] => 8 [3] => 6 [4] => 4 [5] => 2 [6] => 1 ) |
理解:
第1轮比较完成,一定会找到最小值,并保存在数组最后一位;
第2轮比较完成,一定会找到第2小的值,并保存在数组倒数第二位;
……
大循环轮数(固定)是数组元素个数减1次($count-1次),for中使用$count>1来结束大循环。
小循环次数(变化)是($count-1)次,$count每次递减1
$arr = [1,4,8,9,7,10,3,6,2,5,29];
print_r($arr); //
echo ‘<br>’; //
$count = count($arr);
for(;$count>1;$count–){
echo ‘$count=’ . $count;
for($i=1;$i<$count;$i++){
if($arr[$i]>$arr[$i-1]){
$tmp = $arr[$i];
$arr[$i] = $arr[$i-1];
$arr[$i-1] = $tmp;
}
echo ‘<br>’; //
print_r($arr); //
}
echo ‘<br>’; //
}