Program opened below. You can scroll through the algorithm, Java code and output.
Program 74
Sort Boundary Elements of a Matrix
Question
Accept a square matrix of order N (4 <= N <= 9). Sort all boundary elements in ascending order and place them back in boundary positions in row-major order; display the updated matrix and diagonal sums as required.
Algorithm
Step 1: Start.
Step 2: Declare the variables and data structures required for the task.
Step 3: Input N and validate its range.
Step 4: Input and display the matrix.
Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution.
Step 6: Collect elements from the first row, last row, first column and last column without duplicating corners.
Step 7: Sort the boundary list in ascending order.
Step 8: Traverse boundary positions in row-major order and replace them with sorted values.
Step 9: Display the rearranged matrix.
Step 10: Calculate and display the diagonal sums.
Step 11: Stop.
Java program
Javaimport java.util.*;
class SortBoundary {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n < 4 || n > 9) {
System.out.println("SIZE OUT OF RANGE");
return;
}
int[][] a = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
}
}
ArrayList<Integer> b = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == n - 1 || j == n - 1) {
b.add(a[i][j]);
}
}
}
Collections.sort(b);
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == n - 1 || j == n - 1) {
a[i][j] = b.get(k++);
}
}
}
int left = 0, right = 0;
for (int i = 0; i < n; i++) {
left += a[i][i];
right += a[i][n - 1 - i];
}
for (int[] row : a) {
for (int v : row) {
System.out.print(v + " ");
}
System.out.println();
}
System.out.println("LEFT DIAGONAL SUM = " + left);
System.out.println("RIGHT DIAGONAL SUM = " + right);
}
}Sample output
Output:
REARRANGED MATRIX
...
LEFT DIAGONAL SUM = ...
RIGHT DIAGONAL SUM = ...