Given a matrix of custom size the task is to sort each row of the matrix in ascending order.
Example:
| 5 | 7 | 1 |
| 8 | 2 | 9 |
→
| 1 | 5 | 7 |
| 2 | 8 | 9 |
Java
import java.util.*;
public class SortMatrixAER
{
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;
}
}
}
}
System.out.println("Each row 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