Sorting Boundary Elements of a Matrix and Finding Their Sum Program in Java and Python
Boundary elements of a matrix sorted in descending order with sum, algorithm, explanation, Java program and Python code.
Question:
Write a program to declare a square matrix A[][] of order (M x M) where ‘M’ must be greater than 3 and less than 10. Allow the user to input positive integers into this matrix. Perform the following tasks on the matrix:
(a) Sort the boundary elements in descending order using any standard sorting technique and rearrange them in the matrix.
(b) Calculate the sum of the boundary elements.
(c) Display the original matrix, rearranged matrix and sum of the boundary elements.
Test your program with the sample data and some random data:
Example 1
INPUT :M = 4
OUTPUT:
ORIGINAL MATRIX
REARRANGED MATRIX
Algorithm:
Step 1: Start.
Step 2: Input the order m of the square matrix.
Step 3: If m is not greater than 3 and less than 10, display an invalid range message and stop.
Step 4: Input all elements of the matrix and display the original matrix.
Step 5: Traverse the first row, last column, last row and first column to collect the boundary elements.
Step 6: Add these boundary elements to find their sum.
Step 7: Sort the collected boundary elements in descending order.
Step 8: Place the sorted values back on the boundary positions in clockwise order, without changing the inner elements.
Step 9: Display the rearranged matrix and the sum of the boundary elements.
Step 10: Stop.
Explanation:
The matrix contains two types of positions: boundary positions and inner positions. Boundary positions are the cells in the first row, last row, first column and last column. The task asks us to sort only these boundary values in descending order, so the inner part of the matrix must remain unchanged. The program therefore copies the boundary values into a one-dimensional array first. This makes sorting easier because a standard sorting technique can be applied to a simple list instead of directly sorting the two-dimensional matrix.
After collecting the boundary values, the program calculates their sum and sorts them from largest to smallest. The sorted values are then inserted back into the matrix along the same boundary path: top row from left to right, right column from top to bottom, bottom row from right to left and left column from bottom to top. This path covers every boundary cell exactly once. Finally, the original matrix, the rearranged matrix and the boundary sum are displayed. This approach is clean because matrix traversal, sorting and replacement are handled as separate logical steps, which also makes the solution easier to explain in an ISC practical answer.
While writing the algorithm, the most important detail is to avoid collecting corner elements twice. The clockwise traversal starts with the complete first row, then takes the last column from the second row onward, then the last row in reverse excluding the already used last corner, and finally the first column upwards excluding both corners. The same path is used while placing the sorted elements back. This symmetry between extraction and replacement keeps the output predictable and prevents off-by-one mistakes in the matrix boundary.
Programming Code:
/**The class SortBoundary, sorts the boundary elements of a 2-D square matrix in descending order.
* It also finds the sum of the boundary elements
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.util.*;
class SortBoundary
{
int A[][], B[], m, n;
static int sum=0;
void input() //Function for taking all the necessary inputs
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the square matrix : ");
m=sc.nextInt();
if(m<4 || m>10)
{
System.out.println("Invalid Range");
System.exit(0);
}
else
{
A = new int[m][m];
n = m*m;
B = new int[n]; // 1-D Array to store Boundary Elements
System.out.println("Enter the elements of the Matrix : ");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print("Enter a value : ");
A[i][j]=sc.nextInt();
}
}
}
}
/* The below function is used to store Boundary elements
* from array A[][] to array B[]
*/
void convert()
{
int x=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
if(i == 0 || j == 0 || i == m-1 || j == m-1) // Condition for boundary elements
{
B[x] = A[i][j];
x++;
sum = sum + A[i][j]; // Finding sum of boundary elements
}
}
}
}
void sortArray() //Function for sorting Boundary elements stored in array B[]
{
int c = 0;
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(B[i]<B[j]) // for ascending use B[i]>B[j]
{
c = B[i];
B[i] = B[j];
B[j] = c;
}
}
}
}
/* Function fillSpiral is filling the boundary of 2-D array in spiral
* way from the elements of 1-D array
*/
void fillSpiral()
{
int R1=0, R2=m-1, C1=0, C2=m-1, x=0;
for(int i=C1;i<=C2;i++) // accessing the top row
{
A[R1][i]=B[x++];
}
for(int i =R1+1;i<=R2;i++) // accessing the right column
{
A[i][C2]=B[x++];
}
for(int i =C2-1;i>=C1;i--) // accessing the bottom row
{
A[R2][i]=B[x++];
}
for(int i =R2-1;i>=R1+1;i--) // accessing the left column
{
A[i][C1]=B[x++];
}
}
void printArray() //Function for printing the array A[][]
{
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
}
public static void main(String args[])
{
SortBoundary ob = new SortBoundary();
ob.input();
System.out.println("*********************");
System.out.println("The original matrix:");
System.out.println("*********************");
ob.printArray(); //Printing the original array
ob.convert(); //Storing Boundary elements to a 1-D array
ob.sortArray(); //Sorting the 1-D array (i.e. Boundary Elements)
ob.fillSpiral(); //Storing the sorted Boundary elements back to original 2-D array
System.out.println("*********************");
System.out.println("The Rearranged matrix:");
System.out.println("*********************");
ob.printArray(); //Printing the rearranged array
System.out.println("*********************");
System.out.println("The sum of boundary elements is = "+sum); //Printing the sum of boundary elements
}
}Equivalent Python Program:
def print_matrix(matrix):
for row in matrix:
print(*row, sep=" ")
m = int(input("Enter the size of the square matrix : "))
if m <= 3 or m >= 10:
print("Invalid Range")
else:
matrix = []
print("Enter the elements of the Matrix : ")
for i in range(m):
row = []
for j in range(m):
row.append(int(input("Enter a value : ")))
matrix.append(row)
print("*********************")
print("The original matrix:")
print("*********************")
print_matrix(matrix)
boundary = []
for j in range(m):
boundary.append(matrix[0][j])
for i in range(1, m):
boundary.append(matrix[i][m - 1])
for j in range(m - 2, -1, -1):
boundary.append(matrix[m - 1][j])
for i in range(m - 2, 0, -1):
boundary.append(matrix[i][0])
total = sum(boundary)
boundary.sort(reverse=True)
k = 0
for j in range(m):
matrix[0][j] = boundary[k]
k += 1
for i in range(1, m):
matrix[i][m - 1] = boundary[k]
k += 1
for j in range(m - 2, -1, -1):
matrix[m - 1][j] = boundary[k]
k += 1
for i in range(m - 2, 0, -1):
matrix[i][0] = boundary[k]
k += 1
print("*********************")
print("The Rearranged matrix:")
print("*********************")
print_matrix(matrix)
print("*********************")
print("The sum of boundary elements is =", total)Output:
Enter the size of the square matrix : 4 Enter the elements of the Matrix : Enter a value : 9 Enter a value : 2 Enter a value : 1 Enter a value : 5 Enter a value : 8 Enter a value : 13 Enter a value : 8 Enter a value : 4 Enter a value : 15 Enter a value : 6 Enter a value : 3 Enter a value : 11 Enter a value : 7 Enter a value : 12 Enter a value : 23 Enter a value : 8 ********************* The original matrix: ********************* 9 2 1 5 8 13 8 4 15 6 3 11 7 12 23 8 ********************* The Rearranged matrix: ********************* 23 15 12 11 1 13 8 9 2 6 3 8 4 5 7 8 ********************* The sum of boundary elements is = 105
Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.