[Solved] How to sort elements into C++ matrix?


Here is a simple example for you:

#include <vector>
#include <algorithm>

using namespace std;

//This is the comparation function needed for sort()
bool compareFunction (int i,int j) 
{ 
    return (i<j); 
}

int main()
{
    //let's say you have this matrix
    int matrix[10][10];
    //filling it with random numbers.
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            matrix[i][j] = rand() % 1000;

    //Now we get all the data from the matrix into a vector.
    std::vector<int> vect;
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            vect.push_back(matrix[i][j]);

    //and sort the vector using standart sort() function
    std::sort( vect.begin(), vect.end(), compareFunction );

    //Finally, we put the data back into the matrix
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            matrix[i][j] = vect.at(i*10 + j);
}

After this, the matrix will be sorted by rows:

1 2
3 4

If you want it to be sorted by cols:

1 3
2 4

You need to replace matrix[i][j] in the last cycle only with matrix[j][i]

If you need to read about the the sort() function, you can do it here
Hope this helps.

2

solved How to sort elements into C++ matrix?