Categories

# Sort Matrix ISC 2012 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 20. Allow the user to input integers into this matrix. Perform the following tasks on the matrix:

1. Display the input matrix.
2. Find the maximum and minimum value in the matrix and display them along with their position.
3. Sort the elements of the matrix in ascending order using any standard sorting technique and rearrange them in the matrix.
4. Output the rearranged matrix.

Test your program with the sample data and some random data.

Example 1:
INPUT:
M = 3
N = 4

```8    7    9    3
-2   0    4    5
1    3    6   -1```

OUTPUT:
ORIGINAL MATRIX:

```8    7    9    3
-2   0    4    5
1    3    6   -1```

LARGEST NUMBER: 9
ROW = 0
COLUMN = 3
REARRANGED MATRIX:

```-4   -2   0    1
3    3    4    5
6    7    8    9```

Example 2:
INPUT:
M = 3
N = 22
OUTPUT:
SIZE OUT OF RANGE

``````import java.io.*;
class Sort{
public static void main(String args[])throws IOException{
System.out.print("M = ");
System.out.print("N = ");
if(m <3 || n < 3 || m > 19 || n > 19){
System.out.println("SIZE OUT OF RANGE.");
return;
}
int a[][] = new int[m][n];
int single[] = new int[m * n];
int index = 0;
int max = 0;
int min = 0;
int p = 0;
int q = 0;
int r = 0;
int s = 0;
System.out.println("Enter matrix elements:");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
single[index++] = a[i][j];
if(i == 0 && j == 0){
max = a[i][j];
min = a[i][j];
}
else{
if(max < a[i][j]){
max = a[i][j];
p = i;
q = j;
}
if(min > a[i][j]){
min = a[i][j];
r = i;
s = 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("LARGEST NUMBER: " + max);
System.out.println("ROW = " + p);
System.out.println("COLUMN = " + q);
System.out.println("SMALLEST NUMBER: " + min);
System.out.println("ROW = " + r);
System.out.println("COLUMN = " + s);
for(int i = 0; i < single.length; i++){
for(int j = 0; j < single.length - 1 - i; j++){
if(single[j] > single[j + 1]){
int temp = single[j];
single[j] = single[j + 1];
single[j + 1] = temp;
}
}
}
index = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
a[i][j] = single[index++];
}
}
System.out.println("REARRANGED 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();
}
}
}``````