Bubble Sort Display

喜夏-厌秋 提交于 2019-12-11 01:05:45

问题


#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] << ", ";
}

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?


回答1:


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.




回答2:


There is at least one error in the bubble sort. The assignment to data[i+1] is not correct. It should be:

data[i+1] = temp;


来源:https://stackoverflow.com/questions/9612198/bubble-sort-display

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!