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.

One diagonal highlighted Each diagonal is sorted independently

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 ?

  1. Starting from left edge: Process diagonals starting from positions (0,0), (1,0), (2,0), etc.
  2. Starting from top edge: Process remaining diagonals starting from positions (0,1), (0,2), (0,3), etc.
  3. 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.

Updated on: 2026-03-25T11:01:20+05:30

605 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements