本帖最后由 Sian 于 2015-12-30 17:12 编辑
[PHP] 纯文本查看 复制代码 <?php
$number = array(5, 1, 7, 3, 4, 0, 6, 2, 8, 9);
echo "原数组:";
print_r($number);
echo "<br/>";
function mysort($array){
// 计算数组个数
$count = count($array) - 1;
// 重复冒泡会将整个数组中的小数字都往后移
for ($j = 0; $i < $count; $i ++){
// 取出相临两个进行对比,将小数字放后面
// 循环操作,从头到尾进行一轮比较后
// 最小的数字一定会被转移到最后面
// 这个过程形象地叫做冒泡
for($j = 0; $j < $count - $i; $j++){
if ($array[$j] < $array[$j+1]){
// 三部操作将两数字进行调换
$tmp = $array[$j];
$array[$j] = $array[$j+1];
$array[$j+1] = $tmp;
}
echo "$array[$j] ";
}
echo "<br/>";
print_r($array);
echo "<br/>";
}
return $array;
}
echo "<br/>";
echo "开始排序:<br/>";
$sort = mysort($number);
echo "<br/>";
echo "排序后的数组:<br/>";
print_r($sort);
输出结果为:
原数组:Array ( [0] => 5 [1] => 1 [2] => 7 [3] => 3 [4] => 4 [5] => 0 [6] => 6 [7] => 2 [8] => 8 [9] => 9 )
开始排序:
5 7 3 4 1 6 2 8 9
Array ( [0] => 5 [1] => 7 [2] => 3 [3] => 4 [4] => 1 [5] => 6 [6] => 2 [7] => 8 [8] => 9 [9] => 0 )
7 5 4 3 6 2 8 9
Array ( [0] => 7 [1] => 5 [2] => 4 [3] => 3 [4] => 6 [5] => 2 [6] => 8 [7] => 9 [8] => 1 [9] => 0 )
7 5 4 6 3 8 9
Array ( [0] => 7 [1] => 5 [2] => 4 [3] => 6 [4] => 3 [5] => 8 [6] => 9 [7] => 2 [8] => 1 [9] => 0 )
7 5 6 4 8 9
Array ( [0] => 7 [1] => 5 [2] => 6 [3] => 4 [4] => 8 [5] => 9 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
7 6 5 8 9
Array ( [0] => 7 [1] => 6 [2] => 5 [3] => 8 [4] => 9 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
7 6 8 9
Array ( [0] => 7 [1] => 6 [2] => 8 [3] => 9 [4] => 5 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
7 8 9
Array ( [0] => 7 [1] => 8 [2] => 9 [3] => 6 [4] => 5 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
8 9
Array ( [0] => 8 [1] => 9 [2] => 7 [3] => 6 [4] => 5 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
9
Array ( [0] => 9 [1] => 8 [2] => 7 [3] => 6 [4] => 5 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
排序后的数组:
Array ( [0] => 9 [1] => 8 [2] => 7 [3] => 6 [4] => 5 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 ) |