$arr = [2,376,3,1,65,123,758,1234,7856,123]; //冒泡 //逐行对比,满足条件则交换 function bubbleSort($arrData,$sort = 'desc') { if(empty($arrData)) return $arrData; //默认有序 $isSorted = true; $nCount = count($arrData); for($i = 0; $i < $nCount; $i++) { //对比次数随着循环逐渐减少,因为后面的数据已经处理为有序 for($j = 0; $j < ($nCount - $i - 1); $j++) { //执行判断 $isChange = $sort == 'desc' ? $arrData[$j] < $arrData[$j+1] : $arrData[$j] > $arrData[$j+1]; if($isChange) { //首次对比,判断是否有序 $isSorted = false; $temp = $arrData[$j]; $arrData[$j] = $arrData[$j+1]; $arrData[$j+1] = $temp; } } if($isSorted) break; } return $arrData; } $arr = bubbleSort($arr,'asc'); print_r($arr);