气泡排序显示 [英] Bubble Sort Display

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

问题描述

#include <iostream>
#include <string>

using namespace std;

void bubbleSort(int data[], int n);

int main()
{
cout << "Enter ten unsorted integers..." << endl;

int a[10];
for (int i = 0; i < 10; ++  i)
{
    cout << "[" << i << "] = ";
    cin >> a[i];
}

cout << endl << "Unsorted List = ";
    for (int i = 0; i < 10; ++i)
    cout << a[i] << ", ";

cout << endl;

cout << "Sorting..." << endl;
cout << "Sorted List = ";
bubbleSort(a, 10);
}

void bubbleSort(int data[], int n)
{
int j = 0;
bool nextEnd = true;
while (nextEnd)
{
    nextEnd = false;
    ++j;
    for (int i = 0; i < n - j; ++i) 
    {
        if (data[i] > data[i+1]) 
        {
            int temp = data[i];
            data[i] = data[i+1];
            data[i+1] = data[i];
            nextEnd = true;
        }
    }
}

for (int i = 0; i < 10; ++i)
cout << data[i] << ", ";
}

该程序非常简单。向数组输入十个值。显示它们未排序。将它们发送到bubbleSort函数中,对其进行排序,最后显示排序后的列表。我遇到的问题是我无法恢复输出。我测试了最后一行代码,但是没有用。我也不认为我的排序很混乱。如何正确显示此排序列表?

The program is really simple. Input ten values to an array. Display them unsorted. Send them into the bubbleSort function, sort them and finally display the sorted list. The problem I'm having is I don't get the outputting back to work. I tested with the last line of code but that doesn't work. I don't think my sorting is messed up either. How can I display this sorted list properly?

推荐答案

问题是您的交换。应该是:

The problem is your 'swap'. It should be:

int temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;

经过编辑测试,可以更正。

Edit-Tested and works fine with the correction.

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

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