1

I am trying to use bubble sort to sort a set of random numbers. But my code results in a messed up order. For example, instead of it sorting 9 12 15 100 150,it will sort as 12 15 100 9 150. Any help will be appreciated. Below is my code.

#include <iostream>
#include <cstdlib>
using namespace std;
void sortArray(int[], int);
void showArray(const int[], int);

int main() 
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 200;
int numbers[MAX_VALUE]; 

for (int count = 0; count < MAX_VALUE; count++)
   {
    numbers[count] = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
    cout << numbers[count]<< endl;
    sortArray(numbers, count);
    showArray(numbers, count);
   }

} 

void sortArray(int numbers[], int size)
{
   bool swap;
   int temp;
 do
{
    swap = false;
    for (int count = 0; count < (size -1); count++)
    {

        if (numbers[count] > numbers[count + 1])
        {   
            temp = numbers[count+1];
            numbers[count+1] = numbers[count];
            numbers[count] = temp;
            swap = true;
        }
    }
 } while (swap);

}
void showArray(const int numbers[], int size)
{
 for (int count = 0; count < size; count++)
     cout <<numbers[count] << endl;
}

Thanks

cmw
  • 23
  • 2

1 Answers1

1

The sorting code is correct.

The only problem is that you're calling the sort and printing out the array in the same loop that is filling the data.

You should first fill all the data, then sort, then display the sorted result.

6502
  • 112,025
  • 15
  • 165
  • 265
  • Hi sorry, i am a beginner and it takes me forever to figure out things. So it took me a while to do the necessary changes you mentioned. and it worked. thanks a lot. – cmw May 08 '16 at 22:35