Sort Matrix ISC Computer Science 2021 Practical
Write a program to declare a matrix A[][] of order (M × N) 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 8. Allow the user to input integers into the matrix.
Perform the following tasks on the matrix:
(a) Sort the matrix elements in descending order using any standard sorting technique.
(b) Calculate the sum of the boundary elements of the matrix before sorting and after sorting.
(c) Display the original matrix and the sorted matrix along with the sum of their boundary elements respectively.
Test your program for the following data and some random data:
Example 1
INPUT:
M = 3
N = 4
ENTER ELEMENTS OF MATRIX
11 2 -3 5
1 7 13 6
0 4 9 8
OUTPUT:
ORIGINAL MATRIX
11 2 -3 5
1 7 13 6
0 4 9 8
SUM OF THE BOUNDARY ELEMENTS (UNSORTED) = 43
SORTED MATRIX
13 11 9 8
7 6 5 4
2 1 0 -3
SUM OF THE BOUNDARY ELEMENTS (SORTED) = 52
Example 2
INPUT:
M = 3
N = 3
ENTER ELEMENTS OF MATRIX
6 2 5
14 1 17
9 4 8
OUTPUT:
ORIGINAL MATRIX
6 2 5
14 1 17
9 4 8
SUM OF THE BOUNDARY ELEMENTS (UNSORTED) = 65
SORTED MATRIX
17 14 9
8 6 5
4 2 1
SUM OF THE BOUNDARY ELEMENTS (SORTED) = 60
Example 3
INPUT:
M = 2
N = 6
OUTPUT:
OUT OF RANGE
Example 4
INPUT:
M = 4
N = 9
OUTPUT:
OUT OF RANGE
class Matrix{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("M = ");
int m = Integer.parseInt(in.nextLine());
System.out.print("N = ");
int n = Integer.parseInt(in.nextLine());
if(m < 3 || n < 3 || m > 7 || n > 7){
System.out.println("OUT OF RANGE");
return;
}
int a[][] = new int[m][n];
int b[] = new int[m * n];
int sum1 = 0;
int sum2 = 0;
int index = 0;
System.out.println("ENTER ELEMENTS OF MATRIX:");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
a[i][j] = Integer.parseInt(in.nextLine());
b[index++] = a[i][j];
if(i == 0 || i == m - 1 || j == 0 || j == n - 1)
sum1 += a[i][j];
}
}
System.out.println("ORIGINAL MATRIX");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
System.out.println("SUM OF THE BOUNDARY ELEMENTS (UNSORTED) = " + sum1);
for(int i = 0; i < b.length; i++){
for(int j = 0; j < b.length - 1 - i; j++){
if(b[j] < b[j + 1]){
int temp = b[j];
b[j] = b[j + 1];
b[j + 1] = temp;
}
}
}
index = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
a[i][j] = b[index++];
if(i == 0 || i == m - 1 || j == 0 || j == n - 1)
sum2 += a[i][j];
}
}
System.out.println("SORTED MATRIX");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
System.out.println("SUM OF THE BOUNDARY ELEMENTS (SORTED) = " + sum2);
}
}
Comments
Post a Comment