Nov 15, 2011 at 3:46am UTC
I need to sort this 2d array [50][40] filled with random numbers.
here's my code so far.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
#include <iostream>
#include <ctime>
using namespace std;
void sort(int [][40], int );
int main()
{
int nums[50][40];
int rows = 50;
srand((unsigned )time(0));
for (int i = 0; i < 50; i++) //used to fill 2d array with random nums
{
for (int j = 0; j < 40; j++)
{
nums[i][j] = rand() % 100;
}
}
for (int i = 0; i < 50; i++) //display "before sorted" array
{
for (int j = 0; j < 40; j++)
{
cout<<nums[i][j]<<' ' ;
}
}
sort(nums, rows);
cout<<"\n-------------------------------\n" ; //I used this as a divider
for (int i = 0; i < 50; i++) //display sorted array
{
for (int j = 0; j < 40; j++)
{
cout<<nums[i][j]<<' ' ;
}
}
cout<<'\n' ;
system ("pause" );
return 0;
}
void sort(int nums[][40], int rows)
{
int hold;
int test[2000];
int count = 0;
for (int i = 0; i < rows; i++)//transfer elements of nums(2d array) to a 1d array
{
for (int j = 0; j < 40; j++)
{
test[count] = nums[i][j];
count++;
}
}
for (int i = 0; i < 1999; i++)//sort test array
{
if (test[i] > test[i+1])
{
hold = test[i];
test[i] = test[i+1];
test[i+1] = hold;
}
}
count = 0;
for (int i = 0; i < rows; i++)//re-transfer sorted array to 2d array
{
for (int j = 0; j < 40; j++)
{
nums[i][j] = test[count];
count++;
}
}
}
Why isn't my code sorting the test array (in void sort function) properly?
Things swap around but not properly placed...
Last edited on Nov 15, 2011 at 3:50am UTC
Nov 15, 2011 at 3:55am UTC
I am also a newbie, but it may be because you are trying to define i more than once. There is probably no need to keep saying "int i".
Last edited on Nov 15, 2011 at 3:55am UTC
Nov 15, 2011 at 3:59am UTC
I changed things up and still didn't sort properly
Nov 15, 2011 at 4:10am UTC
Okay, I changed from my bubble sort to a selection sort(which, I had no idea what it was) and it worked (basically copied the code from my text).
I don't know but it did the trick!!!
However, I still want to know what went wrong here...
(Perhaps, bubble sort was too much work?)
Nov 15, 2011 at 5:56am UTC
I think when you sort your test arrays, you only compare the current array to the next array, but if the if statement were to execute more than once you'll have problems with the sort. Try using a smaller array size and check the numbers by hand. Prob having a for loop in between the tmp will help?
for example, if you array was:
8 3 9 2 8 9 4 --> 8>3
3 8 9 2 8 9 4 --> 8<9
3 8 9 2 8 9 4 --> 9>2
3 8 2 9 8 9 4 --> 9>8
3 8 2 8 9 9 4 --> 9=9
3 8 2 8 9 9 4 --> 9>4
3 8 2 8 9 4 9
I hope that's right :/
Last edited on Nov 15, 2011 at 6:01am UTC