为什么不能有一个循环进行泡沫排序? [英] Why cant you have one loop for bubble sort?

查看:176
本文介绍了为什么不能有一个循环进行泡沫排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在与我的导师讨论气泡排序,他告诉我说,气泡排序被称为两个for循环,一个嵌套在另一个。在我开始作业之前没有给出,所以好的,这是罚款,但这个代码为泡沫排序有什么问题:

I was just in an argument with my instructor about bubble sort, he told me that bubble sort is known as two for loops, one nested in the other. Which was not given before I started the assignment, so okay that is fine, but what is wrong with this code for a bubble sort:

int num = 0, i = 0;
bool go = true;
while (i < size - 1){
    if (array[i] > array[i + 1]){
        num = array[i];
        array[i] = array[i + 1];
        array[i + 1] = num;
        go = false;
    }
    i++;
    if (i >= size - 1 && go == false){
        i = 0;
        go = true;
    }
}

for (int i = 0; i < size; i++){
    cout << array[i];
}

它不会做一个气泡排序相同的事吗?

does it not do the same thing as a bubble sort?

int i, j;
bool flag = true;
int temp;
int numLength = size;
for (i = 1; (i <= numLength) && flag; i++)
{
    flag = false;
    for (j = 0; j < (numLength - 1); j++)
    {
        if (array[j + 1] < array[j])
        {
            temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
            flag = true;
        }
    }
}

for (int i = 0; i < size; i++){
    cout << array[i];
}

return;


$ b

谢谢!

Thanks!

推荐答案

气泡排序算法需要两个循环:内部循环遍历项目,如果相邻的项目出现故障,则交换它们,外部循环重复,直到不再进行更改。

The bubble sort algorithm needs two loops: the inner one iterating through the items and swapping them if adjacent ones are out of order, the outer one repeating until no more changes are made.

您的实施 有效地有两个循环。它只是其中之一是使用一个标志和if条件,重置外部循环变量实现。它会做同样的事情 - 循环通过项目,直到不再需要交换。

Your implementation does effectively have two loops. It's just that one of them is implemented using a flag and if condition, which resets the outer loop variable. It will do the same thing - loop through the items until no more need swapping.

但是,以这种方式构建算法不会使它更高效,或更快,或任何类似的。它只是使我们很难弄清楚发生了什么。

Note, however, that constructing the algorithm in this way does not make it more efficient, or faster, or anything like that. It just makes it harder to figure out what is going on.

这篇关于为什么不能有一个循环进行泡沫排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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