<?php function getRandArr(){ $num = mt_rand(10,11); $arr = array(); for($i = 0;$i < $num;$i++){ $arr[$i] = mt_rand(100,100000); } return $arr; } //冒泡排序 function bubbleSort($arr,$asc = TRUE){ $last_key = count($arr) - 1; if($asc == TRUE){ //升序 for($i = 0;$i <= $last_key;$i++){ //获取已经排序号的key $sort_key = $last_key - $i; for($j = 0;$j < $sort_key;$j++){ if($arr[$j] > $arr[($j + 1)]){ //下一个大于上一个 $temp = $arr[($j + 1)]; $arr[($j + 1)] = $arr[$j]; $arr[$j] = $temp; } } } }else{ //降序 for($i = $last_key;$i >= 0;$i--){ //获取已经排序好的key $sort_key = $last_key - $i; for($j = $last_key;$j > $sort_key;$j--){ if($arr[$j] > $arr[($j - 1)]){ //下一个大于上一个 $temp = $arr[($j - 1)]; $arr[($j - 1)] = $arr[$j]; $arr[$j] = $temp; } } } } return $arr; } $sort_arr = getRandArr(); var_dump(bubbleSort($sort_arr));
The above introduces how to write bubble sort in PHP, including bubble sort and PHP content. I hope it will be helpful to friends who are interested in PHP tutorials.