Bubble Sort Display

2019-07-19 13:28发布

#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?

2条回答
贼婆χ
2楼-- · 2019-07-19 13:54

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;
查看更多
【Aperson】
3楼-- · 2019-07-19 14:18

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.

查看更多
登录 后发表回答