Szymon Żurawski
Szymon Żurawski

Reputation: 23

Sorting columns of a matrix according to a particular row in c++

Is there a simple way to sort matrix in c++ according to eg. first row, so that all elements rearrange accordingly?

Example:

int matrix[3][3] = { {5,2,4},
                     {1,7,8},
                     {9,2,6} };

After sorting by first row it would look like this:

{2,4,5},
{7,8,1},
{2,6,9}

Preferably, I'd like to use sort() function, and I don't mind using vectors if it would make the task easier.

Upvotes: 1

Views: 487

Answers (1)

nekotizimo
nekotizimo

Reputation: 26

As the comments said, it's easier to sort a matrix by a column than by a row, since std::sort with the use of a lambda function will do the job for the former.

My recommendation is to sort the column indices by the row, then use the sorted indices to rebuild the matrix:

#include <algorithm>
using namespace std;
const int n = 3; // size of matrix
int sort_by_row = 0; // row to sort by
int original[n][n] = { {5,2,4},
                        {1,7,8},
                        {9,2,6} };
int main() {
    int col_indices[n];
    for (int i = 0; i < n; i++) col_indices[i] = i; // create column indices 0...n-1
    sort(col_indices, col_indices + n, [] (const int &a, const int &b) { // sort indices by row
        return original[sort_by_row][a] < original[sort_by_row][b];
    });
    
    int sorted[n][n]; // rebuild matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            sorted[i][j] = original[i][col_indices[j]];
        }
    }
}

In this method, you iterate over the matrix once only, whereas if you transpose the matrix, sort, then transpose it back, you iterate over the matrix twice (during transposition).

Upvotes: 1

Related Questions