Mogovan Jonathan
Mogovan Jonathan

Reputation: 173

How to sort a 2d matrix by column?

I have this following code where i sort a 2d matrix every element inserted in columns.

for example:

5 4 

2 4 1 3
9 8 7 6
20 19 18 16
30 29 124 12
59 21 0 3
0 4 12 21 
1 6 16 29 
2 7 18 30 
3 8 19 59 
3 9 20 124 

My first method of sorting is this one:

vector<vector<int>> w;
vector<int> v;
int n,m,x;

cin >> n >> m;
w.resize(n, vector<int>(m));

for(int i=1; i <= n*m; i++)
    cin >> x,v.push_back(x);

sort(v.begin(), v.end());
int k=0;

for(int i=0; i < m; i++)
{
    for(int j=0;j<n;j++)
        w[j][i]=v[k++];
}

for(int i=0; i < n; i++)
{
    for(int j=0;j<m;j++)
        cout << w[i][j] << " ";
    cout << '\n';
}

my second :

for(int i=0;i<m;i++)
    for(int j=0;j<n;j++)
        for(int k=i;k<m;k++)
        {
            int l;
            if(i==k)
                l=j;
            else
                l=0;
            for(;l<n;l++)
                if(a[j][i]>a[l][k])
                    swap(a[j][i],a[l][k]);
        }

My question is: Isn't there an easier way to sort the 2d matrix, without using two vectors and without using like the second method 3- for (it becomes too slow for thousands of rows)?

Upvotes: 0

Views: 66

Answers (1)

Jarod42
Jarod42

Reputation: 217283

The 2D vector is unneeded, you might display your 1D vector as 2D:

int n,m;
std::cin >> n >> m;
std::vector<int> v;
//v.reserve(n * m);
for (int i = 0; i != n * m; i++) {
    int x;
    std::cin >> x;
    v.push_back(x);
}
std::sort(v.begin(), v.end());
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < m; j++)
        std::cout << v[j * n + i] << " ";
    std::cout << '\n';
}

Demo

Upvotes: 2

Related Questions