Hi.
How to sort a 2D array row by row, not the whole array at once.
Is it possible to use the STL Sort to do this. Thanks.
How to sort a 2D array row by row, not the whole array at once.
Is it possible to use the STL Sort to do this. Thanks.
//If this is the 2 dim array
int a [4][5]={{5,7,3,4,12},{9,7,13,2,8},{6,
14,7,9,15},{4,3,9,11,7}};
//this will print it
void print(int a[4][5],int n)
{
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
{
cout<<a[i][j]<<",";
if(j==4)cout<<"\n";
}
}
....and this will sort it.
void sort_rows(int a[4][5],int n)
{
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
{if(j>0 && a[i][j-1]>a[i][j])
swap(a[i][j-1],a[i][j]);
}
}/*the output is:-
the 2D array is:
5,7,3,4,12,
9,7,13,2,8,
6,14,7,9,15,
4,3,9,11,7,
the sorted rows are:
3,4,5,7,12,
2,7,8,9,13,
6,7,9,14,15,
3,4,7,9,11,
press any key to continue...*/
//But you may need to call sort_rows more than once.
//If this is the 2 dim array
int a [4][5]={{5,7,3,4,12},{9,7,13,2,8},{6,
14,7,9,15},{4,3,9,11,7}};
//this will print it
void print(int a[4][5],int n)
{
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
{
cout<<a[i][j]<<",";
if(j==4)cout<<"\n";
}
}
....and this will sort it.
void sort_rows(int a[4][5],int n)
{
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
{if(j>0 && a[i][j-1]>a[i][j])
swap(a[i][j-1],a[i][j]);
}
}/*the output is:-
the 2D array is:
5,7,3,4,12,
9,7,13,2,8,
6,14,7,9,15,
4,3,9,11,7,
the sorted rows are:
3,4,5,7,12,
2,7,8,9,13,
6,7,9,14,15,
3,4,7,9,11,
press any key to continue...*/
//But you may need to call sort_rows more than once.
void swap(int& a, int& b) {
int c = a;
a = b;
b = c;
}
void sort_rows(int a[4][5]) {
for(int i=0;i<4;i++)
for(int z=1;z<5;z++)
for(int j=1;j<5;j++)
{
if (a[i][j-1]>a[i][j])
swap(a[i][j-1],a[i][j]);
}
}
Comment