思路: 从某一方向开始,依次两两比较,把小的放左边,大的放右边(俗称沉石法)
<?php
$disorder = array(7, 3, 4, 9, -2, 5);
$len = sizeof($disorder);
for ($i = 0; $i < $len; $i++) {
for ($j = 0; $j < $len - 1 - $i; $j++) {
if ($disorder[$j] > $disorder[$j + 1]) { // 相邻元素两两比较
$temp = $disorder[$j+1]; // 元素交换
$disorder[$j+1] = $disorder[$j];
$disorder[$j] = $temp;
}
}
}
print_r($disorder);
运行结果:Array ( [0] =˃ -2 [1] =˃ 3 [2] =˃ 4 [3] =˃ 5 [4] =˃ 7 [5] =˃ 9 )