Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to sort each diagonal elements in ascending order of a matrix in C++
Matrix diagonal sorting is a problem where we need to sort each diagonal of a matrix from top-left to bottom-right in ascending order. Each diagonal runs parallel to the main diagonal and gets sorted independently.
Understanding the Problem
Given a matrix, we identify all diagonals that run from top-left to bottom-right. For example, in a 3x4 matrix, we have multiple diagonals starting from different positions.
Example Input and Output
Consider the input matrix ?
| 3 | 3 | 1 | 1 |
| 2 | 2 | 1 | 2 |
| 1 | 1 | 1 | 2 |
After sorting each diagonal, the output matrix becomes ?
| 1 | 1 | 1 | 1 |
| 1 | 2 | 2 | 2 |
| 1 | 2 | 3 | 3 |
Algorithm Steps
The solution involves these key steps ?
- Identify each diagonal starting point
- Extract elements from each diagonal into a temporary array
- Sort the temporary array
- Place sorted elements back into the diagonal positions
Python Implementation
def diagonal_sort(matrix):
def sort_diagonal(start_row, start_col):
# Extract diagonal elements
temp = []
row, col = start_row, start_col
while row < len(matrix) and col < len(matrix[0]):
temp.append(matrix[row][col])
row += 1
col += 1
# Sort the diagonal elements
temp.sort()
# Place sorted elements back
row, col = start_row, start_col
index = 0
while row < len(matrix) and col < len(matrix[0]):
matrix[row][col] = temp[index]
row += 1
col += 1
index += 1
rows = len(matrix)
cols = len(matrix[0])
# Sort diagonals starting from first column
for i in range(rows):
sort_diagonal(i, 0)
# Sort diagonals starting from first row (except first cell)
for j in range(1, cols):
sort_diagonal(0, j)
return matrix
# Example usage
matrix = [
[3, 3, 1, 1],
[2, 2, 1, 2],
[1, 1, 1, 2]
]
result = diagonal_sort(matrix)
for row in result:
print(row)
[1, 1, 1, 1] [1, 2, 2, 2] [1, 2, 3, 3]
How It Works
The algorithm processes each diagonal by ?
- Starting from left edge: Process diagonals starting from positions (0,0), (1,0), (2,0), etc.
- Starting from top edge: Process remaining diagonals starting from positions (0,1), (0,2), (0,3), etc.
- Extract and sort: For each diagonal, collect elements, sort them, and place them back
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(mn log(min(m,n))) | Each element is sorted once in its diagonal |
| Space | O(min(m,n)) | Temporary array for longest diagonal |
Conclusion
Diagonal matrix sorting efficiently sorts each diagonal independently using a two-phase approach. The algorithm processes diagonals starting from the left edge and top edge, ensuring all elements are sorted within their respective diagonals.
