Sort Matrix Boundary Elements in Java

Write a program to declare a square matrix a[][] of order [M × M]. Allow the user to input positive integers into this matrix. Perform the following tasks on the matrix:

  1. Sort the boundary elements in descending order using any standard sorting technique and rearrange them in the matrix.
  2. Calculate he sum of the boundary elements.
  3. Display the original matrix, rearranged matrix and the sum of the boundary elements.
import java.io.*;
class Boundary{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("M = ");
        int m = Integer.parseInt(br.readLine());
        int a[][] = new int[m][m];
        int b[] = new int[2 * m + 2 * (m - 2)];
        int index = 0;
        int sum = 0;
        System.out.println("Enter positive integers:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                a[i][j] = Math.abs(Integer.parseInt(br.readLine()));
                if(i == 0 || j == 0 || i == m - 1 || j == m - 1){
                    b[index++] = a[i][j];
                    sum += a[i][j];
                }
            }
        }
        System.out.println("Original matrix:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
        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++)
            a[0][i] = b[index++];
        for(int i = 1; i < m; i++) 
            a[i][m - 1] = b[index++]; 
        for(int i = m - 2; i >= 0; i--)
            a[m - 1][i] = b[index++];
        for(int i = m - 2; i >= 1; i--)
            a[i][0] = b[index++];
        System.out.println("Rearranged matrix:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
        System.out.println("Sum of boundary elements: " + sum);
    }
}

Leave a Reply

%d bloggers like this: