For my class I need my program to fill a matrix with random numbers then organize those numbers in descending order. It took quite a bit of time to get my sorting to work, but I still have one problem. It replaces the smallest number with a huge number that it grabbed from outside the matrix, then moves that number to where the largest should be. This only happens if I make the dimensions of the matrix two even numbers tho. Anyway, I'm hoping someone can help me with a fix as my brain hurts from this. Also, I need to have maxcount initialized at 0 but mincount at 1 which I'm not sure why, so if someone could figure that out that'd be good too, but not as important.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int counter=0;
int i, j, width, height, max=0, min=65, maxcount= 0, mincount=1;
int holdi, holdj, hold;
cout << "Enter width of matrix you want. ";
cin >> width;
cout << "Enter height of matrix you want. ";
cin >> height;
int matrix[height][width];
srand(time(NULL));
//This will generate a matrix of random numbers.
for(i = 0; i < height; i++)
{
cout << endl;
for(j = 0; j < width; j++)
{
matrix[i][j] = (rand()%64) + 1;
if(matrix[i][j] < 10)
{
cout << matrix[i][j] << " ";
}
else
{
cout << matrix[i][j] << " ";
}
}
}
cout << endl << endl;
//This will organize the numbers.
for(i = 0; i < height; i++)
{
for(j = 0; j < width;)
{
hold = matrix[i][j];
holdi = i;
holdj = j;
j++;
if(matrix[i][j] > hold)
{
hold = matrix[i][j];
matrix[i][j] = matrix[holdi][holdj];
matrix[holdi][holdj] = hold;
j = 0;
i = 0;
}
}
}
//This will output the new matrix of organized numbers.
cout << "New matrix with numbers organized." << endl;
for(i = 0; i < height; i++)
{
cout << endl;
for(j = 0; j < width; j++)
{
if(matrix[i][j] < 10)
{
cout << matrix[i][j] << " ";
}
else
{
cout << matrix[i][j] << " ";
}
}
}
//Min count.
i = height-1;
j = width-2;
for(min = matrix[height-1][width-1]; matrix[i][j] <= min; j--)
{
mincount = mincount + 1;
}
//Max count.
i = 0;
j = 0;
for(max = matrix[0][0]; matrix[i][j] >= max; j++)
{
maxcount = maxcount + 1;
}
cout << endl << endl << "The maximum number in the matrix is " << max << " and it came up " << maxcount << " times." << endl;
cout << "The minimum number in the matrix is " << min << " and it came up " << mincount << " times." << endl << endl;
system("PAUSE");
}