Sort the matrix row-wise and column-wise using Python

In this article, we will learn how to sort a matrix both row-wise and column-wise using Python. This technique involves sorting rows first, then transposing the matrix to convert columns into rows, sorting again, and transposing back.

We'll implement a solution using nested for loops and matrix transposition to achieve both row-wise and column-wise sorting of an MxM matrix.

Algorithm

Following are the steps to sort a matrix row-wise and column-wise ?

  • Create a function sortingMatrixByRow() to sort each row of the matrix using bubble sort.

  • Create a function transposeMatrix() to swap rows and columns of the matrix.

  • Create a function sortMatrixRowandColumn() that combines the above functions ?

    • Sort all rows of the matrix
    • Transpose the matrix (columns become rows)
    • Sort all rows again (effectively sorting original columns)
    • Transpose back to restore original orientation
  • Display the original and sorted matrices.

Example

The following program sorts a matrix both row-wise and column-wise using nested loops ?

# Function to sort each row of the matrix
def sortingMatrixByRow(inputMatrix, m):
    # Traverse through each row
    for p in range(m):
        # Sort current row using bubble sort
        for q in range(m-1):
            # Compare adjacent elements in the row
            if inputMatrix[p][q] > inputMatrix[p][q + 1]:
                # Swap elements if they are in wrong order
                tempVariable = inputMatrix[p][q]
                inputMatrix[p][q] = inputMatrix[p][q + 1]
                inputMatrix[p][q + 1] = tempVariable

# Function to transpose the matrix
def transposeMatrix(inputMatrix, m):
    # Traverse through the matrix
    for p in range(m):
        # Traverse from diagonal element to last column
        for q in range(p + 1, m):
            # Swap element at (p,q) with element at (q,p)
            temp = inputMatrix[p][q]
            inputMatrix[p][q] = inputMatrix[q][p]
            inputMatrix[q][p] = temp

# Function to sort matrix both row-wise and column-wise
def sortMatrixRowandColumn(inputMatrix, m):
    # Step 1: Sort all rows
    sortingMatrixByRow(inputMatrix, m)
    
    # Step 2: Transpose matrix (columns become rows)
    transposeMatrix(inputMatrix, m)
    
    # Step 3: Sort rows again (sorting original columns)
    sortingMatrixByRow(inputMatrix, m)
    
    # Step 4: Transpose back to original orientation
    transposeMatrix(inputMatrix, m)

# Function to print the matrix
def printingMatrix(inputMatrix, rows):
    for i in range(rows):
        for j in range(rows):
            print(inputMatrix[i][j], end=" ")
        print()

# Input matrix
inputMatrix = [[2, 6, 5],
               [1, 9, 8],
               [7, 3, 10]]

# Matrix dimensions (3x3)
m = 3

print("Input Matrix:")
printingMatrix(inputMatrix, m)

# Sort the matrix row-wise and column-wise
sortMatrixRowandColumn(inputMatrix, m)

print("Matrix after sorting row-wise and column-wise:")
printingMatrix(inputMatrix, m)
Input Matrix:
2 6 5 
1 9 8 
7 3 10 
Matrix after sorting row-wise and column-wise:
1 5 6 
2 7 9 
3 8 10 

How It Works

The algorithm works by combining row sorting and matrix transposition ?

  1. Initial row sorting: Each row is sorted individually using bubble sort
  2. First transpose: Rows become columns, columns become rows
  3. Second row sorting: Sort the new rows (which were originally columns)
  4. Second transpose: Restore the original matrix orientation

Alternative Approach Using Built-in Functions

For comparison, here's a more concise solution using Python's built-in sort() method ?

import numpy as np

# Input matrix
matrix = [[2, 6, 5],
          [1, 9, 8],
          [7, 3, 10]]

print("Original Matrix:")
for row in matrix:
    print(*row)

# Convert to numpy array for easier manipulation
arr = np.array(matrix)

# Sort rows
for i in range(len(arr)):
    arr[i] = np.sort(arr[i])

# Sort columns
arr = arr.T  # Transpose
for i in range(len(arr)):
    arr[i] = np.sort(arr[i])
arr = arr.T  # Transpose back

print("Sorted Matrix:")
for row in arr:
    print(*row)
Original Matrix:
2 6 5
1 9 8
7 3 10
Sorted Matrix:
1 5 6
2 7 9
3 8 10

Time and Space Complexity

  • Time Complexity: O(n³) where n is the matrix dimension
  • Space Complexity: O(1) as sorting is done in-place

Conclusion

Sorting a matrix both row-wise and column-wise requires sorting rows, transposing the matrix, sorting again, and transposing back. This approach ensures all elements are properly ordered in both dimensions while maintaining the matrix structure.

Updated on: 2026-03-27T00:08:39+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements