Search code examples
c++arrayssortingbubble-sort

Bubble Sort program does not output result


I am in a discrete mathematics class and one of the hw problems is to implement a bubble sort. Here's my futile attempt because it does not output the solution. Please advice. Thank you.

#include <iostream>
#include <cstdlib>
using namespace std;
void BubbleSort();
int array1[100] = {0};
int k;
int main()
{
    cout << "Enter your numbers and when you are done, enter 0000:\n";
    int x = 0;
    int i;
    while (i != 0000)
    {
        cin >> i;
        array1[x] = i;
        x++;
        k = x;
    }
    BubbleSort();
    system("pause");
    return 0;

}

void BubbleSort(){
    int temp;
    for( int i = 0; i < k; i++ ){
        if ( array1[i] > array1[i+1]){
            temp = array1[i+1];
            array1[i+1] = array1[i];
            array1[i] = temp;
        }
    }
    int x = 0;
    while (x <= k)
    {
        cout << array1[x] << "\n";
        x++;
    }
}

Please only use basic programming techniques because this is my first programming class. Thank you. Edit: fixed the relational operator. But now I get incorrect results.


Solution

  • The primary problem is here:

    while (x >! k)
    

    On the first iteration, the condition checks whether (0 > !k), and k is not 0, so !k is 0, so the condition is false and the loop never executes. Try using:

    for (int x = 0; x < k; x++)
        cout << array1[x] << "\n";
    

    You also have a problem in the sort phase of your bubble sort; you only iterate through the data once, which is not enough to sort it, in general.

    Finally, some design issues.

    1. You should have one function to sort the data and a separate function to print it. Don't combine the two functions as you have done here.
    2. Avoid global variables. Pass the array and its operational length to the sort function, and to the print function if you have one.