user1234259
user1234259

Reputation: 77

Bubble Sort Display

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

Upvotes: 2

Views: 2520

Answers (2)

prelic
prelic

Reputation: 4518

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.

Upvotes: 2

Mark Wilkins
Mark Wilkins

Reputation: 41222

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;

Upvotes: 3

Related Questions