求冒泡排序算法用PHP的简单实现

已邀请:
匿名用户

匿名用户

赞同来自:

<?php
//生成10个0到99的随机数到数组$nums;
$nums = array();
for($i = 0; $i< 10; $i++) {
    $nums[ ] = rand(0, 99);
}
echo "排序前:\n";
print_r($nums);

//冒泡排序(爱E族)
for($i = 0; $i < count($nums)-1; $i++ ) {
    for($j = $i+1; $j < count($nums); $j++) {
        //爱E族提示:从小到大排序为'<',从大到小排改成'>'
        if ( $nums[$j] < $nums[$i] ) {
            $tmp = $nums[$j];
            $nums[$j] = $nums[$i];
            $nums[$i] = $tmp;
        }
    }
}
echo "排序后:\n";
print_r($nums);
输出:
排序前:
Array
(
    [0] => 58
    [1] => 56
    [2] => 82
    [3] => 18
    [4] => 86
    [5] => 74
    [6] => 65
    [7] => 94
    [8] => 82
    [9] => 36
)
排序后:
Array
(
    [0] => 18
    [1] => 36
    [2] => 56
    [3] => 58
    [4] => 65
    [5] => 74
    [6] => 82
    [7] => 82
    [8] => 86
    [9] => 94
)

要回复问题请先登录注册