Help with 2D array sorting

I have to make a program that rearranges the rows so that the last column has the numbers in descending order (using the selection sort)

From this
-9 -5 -3
-8 -6 -7
2 0 4

To this
2 0 4
-9 -5 -3
-8 -6 -7

This is what i got 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
  #include <iostream>

using namespace std;

int main()
{int a[100][100],n,m,i,j,aux;
cout<<"How many rows: "; cin>>n;
cout<<"How many columns: "; cin>>m;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
    cout<<"a["<<i<<"]["<<j<<"]="; cin>>a[i][j];
}

for(i=1;i<=n-1;i++)
for(j=i+1;j<=n;j++)
if(a[i][m]<a[j][m])
{ 
    aux=a[j][m];  a[j][m]=a[i][m]; a[i][m]=aux; 
}
for(i=1;i<=n;i++){
for(j=1;j<=m;j++)
{
    cout<<a[i][j]<<" ";
}cout<<endl;}
}

Last edited on
Let me guess, the line 19 should conceptually perform:
Swap rows i and j.

Currently you do swap only one element of those rows (the mth.)
Yes, i swap only one element, but i need to swap the entire row and i don't know how to do that.
Last edited on
same as anything else.
make a temporary 1d array of length row.
copy all the stuff from 1 row into it (for loop, or memcpy for simple types)
copy all the stuff from 2 to 1 (another loop/memcpy)
copy all the stuff from tmp to 2

if you had declared the thing differently it would be possible to swap only pointers (each pointer being a row in and of itself) but doing that has its own complexities. You have to pick your poison.

you can construct an array of pointers and sort that, from the original, and have the best of both worlds with a bit of trouble.
int *t[100];
for(..)
t[i] = a[i];

and then use pointer swaps in t to sort a 'view' of a... does that make sense? A isnt sorted, but t refers back to a in a way that 'looks' sorted. t[a][b] still works same as A. Messing with data in A changes T, and T changes A ... this approach expects you to understand pointers pretty well...

Last edited on
Lets pretend that you could write the
aux=a[j][col]; a[j][col]=a[i][col]; a[i][col]=aux;
as std::swap( a[j][col], a[i][col] );

Would it be logical to
for each col in 1..m
do
  std::swap( a[j][col], a[i][col] );
Last edited on
Topic archived. No new replies allowed.