用冒泡排序对数组排序 [英] Sorting an array with bubble sort

查看:93
本文介绍了用冒泡排序对数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一种算法,该算法显示气泡排序的每个步骤,一次排序一个数字.我能够在第一个索引处对数字进行排序,但是我需要弄清楚如何对所有数字进行排序.

I am trying to create an algorithm that shows each step of bubble sort, sorting one number at a time. I was was able to sort the number at the first index, but I need to figure out how to sort all the numbers.

$x = array (9,7,5,3,0);

$count = count($x);
for($i = 0; $i < $count-1; $i++ ) {
    $temp = $x[$i+1];
    $x[$i+1] = $x[$i];
    $x[$i] = $temp;
    echo '<pre>';
    print_r($x);
}

我当前的输出是:

Array
(
    [0] => 7
    [1] => 9
    [2] => 5
    [3] => 3
    [4] => 0
)
Array
(
    [0] => 7
    [1] => 5
    [2] => 9
    [3] => 3
    [4] => 0
)
Array
(
    [0] => 7
    [1] => 5
    [2] => 3
    [3] => 9
    [4] => 0
)
Array
(
    [0] => 7
    [1] => 5
    [2] => 3
    [3] => 0
    [4] => 9
)

从这里开始,我需要继续对剩余的数字进行排序.对于7,输出应为

From here I need to continue sorting the remaining numbers. For 7, the output should be

57390
53790
53970
53907

然后是3

35079
30579
30759
30795

然后为0,对于所有4行,例如

and then for 0, it should be same for all 4 lines like

03570
03579
03579
03579

[分配的问题.] [1]

[The assigned problem.][1]

推荐答案

两个问题:

  • 仅当值顺序不正确时才应交换值
  • 您需要一个外部循环来重复此内部循环,类似于适当的冒泡排序算法.

您的代码可以进行如下修改,从而生成所需的输出:

Your code can be modified like below so it generates the required output:

$x = array (9,7,5,3,0);

$count = count($x) - 1;
for($times = 0; $times < $count; $times++) {
    for($i = 0; $i < $count; $i++ ) {
        $temp = $x[$i+1];
        if ($temp < $x[$i]) {
            $x[$i+1] = $x[$i];
            $x[$i] = $temp;
        }
        echo implode(" ", $x) . "\n";
    }
    echo "\n";
}

请注意,适当的气泡排序算法将执行较少的迭代.

Note that a proper bubble sort algorithm will perform fewer iterations.

这篇关于用冒泡排序对数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆