I have the following code for a buble sort. I want to make it show the output of
ID: 3916966 • Letter: I
Question
I have the following code for a buble sort. I want to make it show the output of random number before the sort displayed like: The array before sorting is: the 10 random number generated. Then, I want it to show the array being sorted that doesn't output the line until the enter key is hit so it would show the same first random numbers with the first number moving up or down the row but only one at a time. So you would hit enter a number of times to get all your numbers to move. Or I can do this an allow the numbers to move on the screen and sort themselves in to order. I am at a loss on either of these sorts. I can do the regular sort as I have below but I cannot get it to fit with either of these two models. Here is what I have:
#include <iostream>
#include <ctime>
#include <string>
#include <windows.h>
using namespace std;
//Output contents function
void output(int data[])
{
for (int i = 0; i < 10; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
int main()
{
//10 numbers at random
int data[10];
srand(time(NULL));
for (int i = 0; i < 10; i++)
{
//numbers between 1 and 100
data[i] = 1 + rand()% 100;
}
output(data);
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 9 - i; j++)
{
if (data[j] > data[j + 1])
{
int temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
for (int j = 0; j < 10; j++)
{
cout << data[j] << " ";
}
Sleep(2);
cout << " " << std::flush << endl;
}
output(data);
return 0;
}
Explanation / Answer
here is your modified code: ---------->>>>>>>>
#include <iostream>
#include <ctime>
#include <string>
#include <windows.h>
using namespace std;
//Output contents function
void output(int data[])
{
for (int i = 0; i < 10; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
int main()
{
//10 numbers at random
int data[10];
srand(time(NULL));
for (int i = 0; i < 10; i++)
{
//numbers between 1 and 100
data[i] = 1 + rand()% 100;
}
output(data);
cout<<" Above Array is being sorted as below : ";
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 9 - i; j++)
{
if (data[j] > data[j + 1])
{
int temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
//system("cls");
output(data);
//cin.get();
cin.ignore();
}
}
}
cout<<" Sorted Array : ";
output(data);
return 0;
}