php冒泡排序
/* * 冒泡排序 */ $arr = array(4,5,2,15,9); $len = count($arr); //从后往前冒泡 $i从0开始 for ($i = 0; $i < $len; $i++){ for($j = $len - 1; $j > $i; $j--){ if($arr[$j] < $arr[$j-1]){ $tmp = $arr[$j]; $arr[$j] = $arr[$j-1]; $arr[$j-1] = $tmp; } } } //从前往后冒泡 $i从1开始 for ($i = 1; $i < $len; $i++){ for ($j = 0; $j < $len - $i; $j++){ if($arr[$j] > $arr[$j+1]){ $tmp = $arr[$j+1]; $arr[$j+1] = $arr[$j]; $arr[$j] = $tmp; } } } print_r($arr);//Array ( [0] => 2 [1] => 4 [2] => 5 [3] => 9 [4] => 15 )
If the copyright belongs to the longfei, please indicate the source!!!