How can I sort a 2D matrix by last column using a comparable function instead of using position arrays?
4 20 15 23 18 9 89
1 8 23 22 14 18 86
17 15 13 18 12 15 90
3 18 8 20 12 5 66
This is my example of 2D matrix where the last column represents the sum of the elements of row i = 1 -> n. I have to sort the rows in ascending order comparing the elements of the last column.
EDIT!
First code was this one:
int main()
{
int x[101][101],y[101],z[101],n,m;
int i,I,j,l,Mi=1000001,b=0;
int s=0;
cin>>n>>m;
for(i=1;i<=n;i++)
for(I=1;I<=m;I++)
cin>>x[i][I];
for(i=1;i<=n;i++)
{
s=0;
for(I=1;I<=m;I++)
s=s+x[i][I];
y[i]=s;
}
for(l=1;l<=n;l++)
{
Mi=1000001;
for(j=1;j<=n;j++)
if(y[j]<Mi)
{
Mi=y[j];
b=j;
}
z[l]=b;
y[b]=1000002;
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
cout<<x[z[i]][j]<<" ";
cout<<endl;
}
return 0;
}
But as i said..i used possition arrays which are not the best thing to use because they use a lot of space and I don't want that. The array is an integer array. I got stuck because I don't know another method that's why I wanted to reach for your help.