In: Computer Science
Language for this question is Java
write the code for the given assignment
Given an n x n matrix, where every row and column is sorted in
non-decreasing order. Print all elements of matrix in sorted
order.Input:
The first line of input contains an integer T denoting the number
of test cases. Then T test cases follow. Each test case contains an
integer n denoting the size of the matrix. Then the next line
contains the n x n elements in row wise order.Output:
Print the elements of the matrix in sorted order.Constraints:
1<=T<=100
1<=n<=100
1<=a[n][n]<=100Example:
Input:
2
4
10 20 30 40 15 25 35 45 27 29 37 48 32 33 39 50
3
1 3 4 2 6 7 5 8 9Output:
10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50
1 2 3 4 5 6 7 8 9
// Java program to print the elements of
// a 2 D array or matrix
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Matrix {
   public static void main(String args[]) throws
IOException
   {
       Scanner sc = new
Scanner(System.in);
       int noOfTestCases =
sc.nextInt();
       //taking nooftestcases input from
the user
       //result is for adding sorted array
values
       ArrayList<String> result =
new ArrayList<String>();
       //traversing
       for(int
k=0;k<noOfTestCases;k++)
       {
       int size = sc.nextInt();
       int mat[][] = new
int[size][size];
      
       //converting 2D to 1D for
sorting
       int temp[] = new
int[size*size];
       int index = 0;
       // Loop through all rows
       for (int i = 0; i < mat.length;
i++)
           // Loop through
all elements of current row
           for (int j = 0;
j < mat[i].length; j++)
          
    {
          
    mat[i][j] = sc.nextInt();
          
    temp[index++] = mat[i][j];
          
    }
      
       //doing sorting
       Arrays.sort(temp);
      
       //puting in arraylist for
printg
       String values = "";
       for (int i = 0; i < temp.length;
i++)
          
    values+=temp[i]+" ";
      
       result.add(values);
       }
       //printing results
       for(String i:result)
          
System.out.println(i);
      
   }
}
