Given a matrix of custom size the task is to sort of the matrix both row and column wise in ascending order.
Example:
| 5 | 7 | 9 |
| 8 | 2 | 1 |
| 6 | 3 | 4 |
→
| 1 | 2 | 6 |
| 3 | 4 | 8 |
| 5 | 7 | 9 |
We observe that each row and column of the output matrix is sorted in ascending order.
Java
import java.util.*;
public class SortMatrixARC
{
public static void main(String args[])
{
int row=0,col=0,temp=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter no.of rows: ");
row=sc.nextInt();
System.out.print("Enter no.of columns: ");
col=sc.nextInt();
int ar[][]=new int[row][col];
System.out.println("Enter matrix elements:-");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
ar[i][j]=sc.nextInt();
}
}
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
for(int k=0;k<col-1-j;k++)
{
if(ar[i][k]>ar[i][k+1])
{
temp=ar[i][k];
ar[i][k]=ar[i][k+1];
ar[i][k+1]=temp;
}
}
}
}
for(int i=0;i<col;i++)
{
for(int j=0;j<row;j++)
{
for(int k=0;k<row-1-j;k++)
{
if(ar[k][i]>ar[k+1][i])
{
temp=ar[k][i];
ar[k][i]=ar[k+1][i];
ar[k+1][i]=temp;
}
}
}
}
System.out.println("Each column sorted matrix:-");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
System.out.print(ar[i][j]+" ");
}
System.out.println();
}
}
}Java