Reputation: 25
My program needs to read in the size of an array from the command line, it then should fill the array with random numbers. It should then display the sorted and unsorted contents of the array.
Created one for loop in order to read random numbers into the array and to display unsorted contents. Created a second for loop nested in the first one in order to sort the contents within the array.
#include <time.h>
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main(int argc, char * argv[], char **env)
{
int SIZE = atoi(argv[1]);
int *array = new int[SIZE];
for(int i = 0; i < SIZE; i++)
{
array[i] = rand()% 1000;
cout << i << ": " << array[i] << "\n";
for(int j = 0; j < SIZE; j++)
{
if(array[j] > array[j + 1])
{
swap(array[j], array[j +1]);
}
cout << i << ": " << array[i] << "\n";
}
}
return 0;
}
I expect an output like
0: 350
1: 264
2: 897
0:264
1:350
2:897
I'm getting an output like
0:41
0:41
0:41
0:41
1:46
1:46
1:0
1:0
2:334
2:334
2:334
2:334
Upvotes: 1
Views: 63
Reputation: 104524
Because you are attempting to continually sort the array before it's initialized. Also, you have undefined behavior when j == SIZE-1
because it's illegal to compare array[j] > array[j+1]
at that point. array[j+1]
is an invalid index.
Instead of this:
for(int i = 0; i < SIZE; i++)
{
array[i] = rand()% 1000;
cout << i << ": " << array[i] << "\n";
for(int j = 0; j < SIZE; j++)
{
if(array[j] > array[j + 1])
{
swap(array[j], array[j +1]);
}
cout << i << ": " << array[i] << "\n";
}
}
This instead:
// randomly initialize the array
for(int i = 0; i < SIZE; i++)
{
array[i] = rand()% 1000;
cout << i << ": " << array[i] << "\n";
}
// sort
for (int i = 0; i < SIZE; i++)
{
for(int j = i+1; j < SIZE; j++)
{
if(array[i] > array[j])
{
swap(array[i], array[j]);
}
}
}
// print results
cout << "finished sorting" << endl;
for(int i = 0; i < SIZE; i++)
{
cout << i << ": " << array[i] << "\n";
}
Upvotes: 2
Reputation: 500357
The immediate issue is that your code is attempting to sort the array even before it's been fully initialized.
You need to split your main loop into three:
Separately, you also need to think carefully about the boundary conditions of your loops.
Upvotes: 1