Question
Program to row-wise sorting matrix in ascending order
Matrix
[3, 20, 1]
[13, 5, 4]
[9, 19, 7]
SORTED MATRIX
1 3 20
4 5 13
7 9 19
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class rowSortingInAscendingOrder
{
public static void main(String[] args)
{
int row=0, col=0,i=0,j=0,k=0,temp=0;
int arr[][];
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE ROW OF MATRIX");
row=sc.nextInt();
System.out.println("ENTER THE COLUMN OF MATRIX");
col=sc.nextInt();
arr=new int[row][col];
System.out.println("ENTER THE ELEMENTS IN MATRIX");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
arr[i][j]=sc.nextInt();
}
}
System.out.println("UNSORTED MATRIX ");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
for(k=0;k< row;k++)
{
if(arr[i][j] < arr[i][k])
{
temp=arr[i][j];
arr[i][j]=arr[i][k];
arr[i][k]=temp;
}
}
}
}
System.out.println("SORTED MATRIX ");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}