Related Articles
Sorting boundary elements of a matrix
• Difficulty Level : Expert
• Last Updated : 28 Jan, 2021

Given a matrix mat[][] of size M*N, the task is to sort only the border elements of the matrix in the clockwise direction and print the matrix after sorting again.
Examples:

Input: M = 4, N = 5, Below is the given matrix:

```1 2 3 4 0
1 1 1 1 2
1 2 2 2 4
1 9 3 1 7```

Output:
0 1 1 1 1
9 1 1 1 1
7 2 2 2 2
4 4 3 3 2
Explanation:
For given matrix, border elements are:
(1, 2, 3, 4, 0, 2, 4, 7, 1, 3, 9, 1, 1, 1)
After sorting in clockwise order:
(0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 7, 9)
Input: M = 3, N = 4

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

Output:
0 0 1 2
8 6 9 2
8 7 4 3
Explanation:
For given matrix, border elements are:
(4, 2, 8, 0, 8, 7, 1, 3, 0, 2)
After sorting in clockwise order:
(0, 0, 1, 2, 2, 3, 4, 7, 8, 8)

Approach: The idea is to store all border elements of the given matrix in an array and sort this array then simply print the new matrix using this sorted array as the border elements.
Detailed steps are as follows:

• Traverse the given matrix and push all the boundary elements to an array A[].
• Sort array A[] in ascending order.
• Print first row using first N elements of array A[].
• From second row to second-last row, first print a single element from end of A[], then print N-2 middle elements from original matrix and finally a single element from the front of A[].
• For last row, print middle elements from A[] which are still not printed, in reverse order.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;``void` `printMatrix(``int` `grid[], ``int` `m, ``int` `n)``{``  ``vector<``int``> A;`` ` `  ``// Appending border elements``  ``for` `(``int` `i = 0; i < m; i++) ``  ``{``    ``for` `(``int` `j = 0; j < n; j++) ``    ``{``      ``if` `(j == n - 1 || (i == m - 1) || j == 0``          ``|| i == 0)``        ``A.push_back(grid[i][j]);``    ``}``  ``}`` ` `  ``// Sorting the list``  ``sort(A.begin(), A.end());`` ` `  ``// Printing first row with``  ``// first N elements from A``  ``for` `(``int` `i = 0; i < n; i++)``    ``cout << A[i] << ``" "``;``  ``cout << endl;``  ``// print(*A[:n])`` ` `  ``// Printing N-2 rows``  ``for` `(``int` `i = 0; i < m - 2; i++) ``  ``{`` ` `    ``// Print elements from last``    ``cout << A[A.size() - i - 1] << ``" "``;`` ` `    ``// Print middle elements``    ``// from original matrix``    ``for` `(``int` `j = 1; j < n - 1; j++)``      ``cout << grid[i + 1][j] << ``" "``;`` ` `    ``// Print elements from front``    ``cout << (A[n + i]) << endl;``  ``}`` ` `  ``// Printing last row``  ``reverse(A.begin() + n + m - 2,``          ``A.begin() + n + m + n - 2);``  ``for` `(``int` `i = n + m - 2; i < n + m - 2 + n; i++)``    ``cout << A[i] << ``" "``;``  ``//[n + m - 2:n + m - 2 + n] << endl;``}`` ` `// Driver Code``int` `main()``{``  ``// Dimensions of a Matrix``  ``int` `m = 4, n = 5;`` ` `  ``// Given Matrix``  ``int` `grid[] = { { 1, 2, 3, 4, 0 },``                   ``{ 1, 1, 1, 1, 2 },``                   ``{ 1, 2, 2, 2, 4 },``                   ``{ 1, 9, 3, 1, 7 } };`` ` `  ``// Function Call``  ``printMatrix(grid, m, n);``  ``return` `0;``}`` ` `// This code is contributed by chitranayal.`

## Python3

 `# Python program for the above approach`` ` `def` `printMatrix(grid, m, n):``     ` `    ``A ``=``[]`` ` `    ``# Appending border elements``    ``for` `i ``in` `range``(m):``        ``for` `j ``in` `range``(n):``            ``if` `j ``=``=` `n``-``1` `or` `(i ``=``=` `m``-``1``                ``) ``or` `j ``=``=` `0` `or` `i ``=``=` `0``:``                ``A.append(grid[i][j])``                 ` `    ``# Sorting the list``     ` `    ``A.sort()`` ` ` ` `    ``# Printing first row with``    ``# first N elements from A``    ``print``(``*``A[:n])`` ` ` ` `    ``# Printing N-2 rows``    ``for` `i ``in` `range``(m``-``2``):``         ` `        ``# Print elements from last``        ``print``(A[``len``(A)``-``i``-``1``],``                          ``end ``=``" "``) ``        ``# Print middle elements``        ``# from original matrix``        ``for` `j ``in` `range``(``1``, n``-``1``):``            ``print``(grid[i ``+` `1``][j],``                          ``end ``=``" "``)``             ` `             ` `        ``# Print elements from front``        ``print``(A[n ``+` `i])`` ` `    ``# Printing last row``    ``print``(``*``reversed``(A[n ``+` `m``-``2``:n ``+` `m``-``2` `+` `n]))`` ` `# Driver Code`` ` `# Dimensions of a Matrix``m, n ``=` `4``, ``5`` ` `# Given Matrix``grid ``=``[[``1``, ``2``, ``3``, ``4``, ``0``],``       ``[``1``, ``1``, ``1``, ``1``, ``2``],``       ``[``1``, ``2``, ``2``, ``2``, ``4``],``       ``[``1``, ``9``, ``3``, ``1``, ``7``]]`` ` `# Function Call``printMatrix(grid, m, n)`
Output:
```0 1 1 1 1
9 1 1 1 1
7 2 2 2 2
4 4 3 3 2```

Time Complexity: O(M*N)
Auxiliary Space: O(M+N)

My Personal Notes arrow_drop_up