Program opened below. You can scroll through the algorithm, Java code and output.
Program 67
Sort Non-Boundary Matrix Elements
Question
Accept a positive square matrix with 4 < M < 10. Sort only the non-boundary elements in ascending order, place them back in their original inner positions, then display the rearranged matrix and the sum of both diagonals.
Algorithm
Step 1: Start.
Step 2: Declare the variables and data structures required for the task.
Step 3: Input M and validate 4 <= M <= 9 as required by the question variant.
Step 4: Input all positive matrix elements and display the original matrix.
Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution.
Step 6: Collect elements whose row and column are both neither first nor last.
Step 7: Sort the collected values in ascending order.
Step 8: Place the sorted values back into the same non-boundary positions in row-major order.
Step 9: Display the rearranged matrix.
Step 10: Calculate the sum of the left and right diagonals.
Step 11: Display diagonal elements and their sum; stop.
Step 12: Stop.
Java program
Javaimport java.util.*;
class SortInnerMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
if (m <= 3 || m >= 10) {
System.out.println("SIZE OUT OF RANGE");
return;
}
int[][] a = new int[m][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = sc.nextInt();
}
}
System.out.println("ORIGINAL MATRIX");
print(a);
ArrayList<Integer> inner = new ArrayList<>();
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
inner.add(a[i][j]);
}
}
Collections.sort(inner);
int k = 0;
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
a[i][j] = inner.get(k++);
}
}
System.out.println("REARRANGED MATRIX");
print(a);
int sum = 0;
System.out.println("DIAGONAL ELEMENTS");
for (int i = 0; i < m; i++) {
System.out.print(a[i][i] + " ");
sum += a[i][i];
if (i != m - 1) {
sum += a[i][m - 1 - i];
}
}
System.out.println("\nSUM OF THE DIAGONAL ELEMENTS = " + sum);
}
static void print(int[][] a) {
for (int[] row : a) {
for (int v : row) {
System.out.print(v + " ");
}
System.out.println();
}
}
}Sample output
Output format:
ORIGINAL MATRIX
...
REARRANGED MATRIX
...
DIAGONAL ELEMENTS
...
SUM OF THE DIAGONAL ELEMENTS = 59