冒泡排序

//定义方法
function bubbleSort($arr) {
    $cnt = count($arr);
    for ($i = 0; $i < $cnt - 1; $i++) {
        for ($j = 0; $j < $cnt - $i - 1; $j++) {
            if ($arr[$j] > $arr[$j + 1]) {
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }
 
    return $arr;
}
 
$arr = array(20, 40, 60, 80, 30, 70, 90, 10, 50, 0);
print_r(bubbleSort($arr));
//输出
Array
(
    [0] => 0
    [1] => 10
    [2] => 20
    [3] => 30
    [4] => 40
    [5] => 50
    [6] => 60
    [7] => 70
    [8] => 80
    [9] => 90
)

Leave comment

Your email address will not be published. Required fields are marked with *.

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据