Write a program to declare a matrix A [][] of order (MXN) where ‘M’ is the number of rows and ‘N’ is the number of columns such that both M and N must be greater than 2 and less than 20. Allow the user to input integers into this matrix. Perform the following tasks on the matrix:
Display the input matrix
Sort the elements of the matrix in ascending order using any standard sorting technique and rearrange them in the matrix.
Output the rearranged matrix.
Test your program with the sample data and some random data:
Example 1.
INPUT:
M=3
N=4
Entered values: 8,7,9,3,-2,0,4,5,1,3,6,-4
OUTPUT:
Original matrix:
8 7 9 3
-2 0 4 5
1 3 6 -4
Rearranged matrix:
-4 -2 0 1
3 3 4 5
6 7 8 9
import java.util.*;
class Matrix
{
int m;
int n;
int arr[][];
Matrix()
{
}
public Matrix( int mm, int nn)
{
m=mm;
n=nn;
arr=new int[m][n];
}
public void accept()
{
Scanner sc=new Scanner(System.in);
{
System.out.println("Enter the number of rows :");
m= sc.nextInt();
System.out.println("Enter the number of columns:");
n= sc.nextInt();
arr=new int[m][n];
for(int i=0;i<m; i++){
for(int j=0;j<n;j++)
{
System.out.println("Enter Value: ");
arr[i][j]= sc.nextInt();
}
}
}
}
void display()
{
System.out.println(" Original Matrix");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
void sort()
{
int i,j,g,h, min;
for(g=0;g<m;g++)
{
for(h=0;h<n;h++)
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(arr[g][h]< arr[i][j])
{
min=arr[g][h];
arr[g][h]=arr[i][j];
arr[i][j]=min;
}
}
}
}
}
}
public static void main(String args[])
{
Matrix ob=new Matrix();
ob.accept();
ob.display();
ob.sort();
ob.display();
}
}