Given a matrix of custom size the task is to sort only the boundary elements of the matrix in ascending order.
Example:
| 5 | 7 | 9 | 0 |
| 8 | 2 | 1 | 4 |
| 6 | 3 | 4 | 8 |
→
| 0 | 3 | 4 | 4 |
| 9 | 2 | 1 | 5 |
| 8 | 8 | 7 | 6 |
Java
import java.util.*;
public class SortMatrixABE
{
public static void main(String args[])
{
int row=0,col=0,n=0,pos=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();
if(row<1||col<1)
{
System.exit(1);
}
int ar[][]=new int[row][col];
n=(row+col-2)*2;
int t[]=new int[n];
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();
if(i==0||j==0||i==row-1||j==col-1)
{
t[pos]=ar[i][j];
pos++;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(t[j]>t[j+1])
{
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
}
}
}
pos=0;
for(int i=0;i<col;i++,pos++)
{
ar[0][i]=t[pos];
}
for(int i=1;i<row-1;i++,pos++)
{
ar[i][col-1]=t[pos];
}
for(int i=col-1;i>=0;i--,pos++)
{
ar[row-1][i]=t[pos];
}
for(int i=row-2;i>0;i--,pos++)
{
ar[i][0]=t[pos];
}
System.out.println("Boundary elements sorted matrix:-");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
System.out.print(ar[i][j]+"\t");
}
System.out.println();
}
}
}Java