Python Program to Sort the matrix row-wise and column-wise
Last Updated :
29 Mar, 2023
Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.
Examples:
Input : mat[][] = { {4, 1, 3},
{9, 6, 8},
{5, 2, 7} }
Output : 1 3 4
2 5 7
6 8 9
Input : mat[][] = { {12, 7, 1, 8},
{20, 9, 11, 2},
{15, 4, 5, 13},
{3, 18, 10, 6} }
Output : 1 5 8 12
2 6 10 15
3 7 11 18
4 9 13 20
Approach: Following are the steps:
- Sort each row of the matrix.
- Get transpose of the matrix.
- Again sort each row of the matrix.
- Again get transpose of the matrix.
Algorithm for getting transpose of the matrix:
for (int i = 0; i < n; i++) {
for (int j = i + 1; i < n; i++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
Python 3
# Python 3 implementation to
# sort the matrix row-wise
# and column-wise
MAX_SIZE = 10
# function to sort each
# row of the matrix
def sortByRow(mat, n):
for i in range (n):
# sorting row number 'i'
for j in range(n-1):
if mat[i][j] > mat[i][j + 1]:
temp = mat[i][j]
mat[i][j] = mat[i][j + 1]
mat[i][j + 1] = temp
# function to find
# transpose of the matrix
def transpose(mat, n):
for i in range (n):
for j in range(i + 1, n):
# swapping element at
# index (i, j) by element
# at index (j, i)
t = mat[i][j]
mat[i][j] = mat[j][i]
mat[j][i] = t
# function to sort
# the matrix row-wise
# and column-wise
def sortMatRowAndColWise(mat, n):
# sort rows of mat[][]
sortByRow(mat, n)
# get transpose of mat[][]
transpose(mat, n)
# again sort rows of mat[][]
sortByRow(mat, n)
# again get transpose of mat[][]
transpose(mat, n)
# function to print the matrix
def printMat(mat, n):
for i in range(n):
for j in range(n):
print(str(mat[i][j] ), end = " ")
print();
# Driver Code
mat = [[ 4, 1, 3 ],
[ 9, 6, 8 ],
[ 5, 2, 7 ]]
n = 3
print("Original Matrix:")
printMat(mat, n)
sortMatRowAndColWise(mat, n)
print("
Matrix After Sorting:")
printMat(mat, n)
# This code is contributed
# by ChitraNayal
Output:
Original Matrix:
4 1 3
9 6 8
5 2 7
Matrix After Sorting:
1 3 4
2 5 7
6 8 9
Time Complexity: O(n2log2n).
Auxiliary Space: O(1). Please refer complete article on Sort the matrix row-wise and column-wise for more details!
Approach 2: Using NumPy
The NumPy code uses the numpy library to sort the matrix rows and transpose the matrix. The NumPy method looks considerably simple.
- np.sort() function is used to sort each row of the matrix and mat.transpose() is used to find the transpose of the matrix.
- The sortMatRowAndColWise function first sorts each row of the matrix using sortByRow function, then finds the transpose of the matrix and again sorts each row of the matrix and finds the transpose.
- The printMat function is used to print the matrix.
Note: Install numpy in python using the following command: pip install numpy
Below is the code for the above approach:
Python3
import numpy as np
# function to sort each row of the matrix
def sortByRow(mat):
return np.sort(mat, axis=1)
# function to sort the matrix row-wise and column-wise
def sortMatRowAndColWise(mat):
# sort rows of mat[][]
mat = sortByRow(mat)
# get transpose of mat[][]
mat = mat.transpose()
# again sort rows of mat[][]
mat = sortByRow(mat)
# again get transpose of mat[][]
mat = mat.transpose()
return mat
# function to print the matrix
def printMat(mat):
print(mat)
# Driver Code
mat = np.array([[ 4, 1, 3 ],
[ 9, 6, 8 ],
[ 5, 2, 7 ]])
print("Original Matrix:")
printMat(mat)
mat = sortMatRowAndColWise(mat)
print("Matrix After Sorting:")
printMat(mat)
# This code is contributed by adityasha4x71
Output:
Output
Time Complexity: O(n^2 log n), where n is the number of elements in the matrix.
Auxiliary Space: O(n^2), as it creates a copy of the transposed matrix.
Similar Reads
How to reverse column order in a matrix with Python? In this article, we will see how to reverse the column order of a matrix in Python. Examples: Input: arr = [[10,20,30], [40,50,60], [70,80,90]] Output: 30 20 10 60 50 40 90 80 70 Input: arr = [[15,30], [45,60], [75,90], [105,120]] Output: 30 15 60 45 90 75 120 105 Matrices are created in python by u
2 min read
heapq in Python to print all elements in sorted order from row and column wise sorted matrix Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order. Examples: Input : mat= [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]] Output : Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30,
2 min read
Sort the Pandas DataFrame by two or more columns In this article, our basic task is to sort the data frame based on two or more columns. For this, Dataframe.sort_values() method is used. This method sorts the data frame in Ascending or Descending order according to the columns passed inside the function. First, Let's Create a Dataframe: Python3 #i
2 min read
Python | Relative sorted order in Matrix Sometimes, while working with Python Matrix, we can have data arranged randomly and we can have a requirement in which we need to get the element position in sorted order of Matrix. Let's discuss a certain way in which this task can be performed. Method : Using list comprehension + enumerate() + sor
4 min read
Sort Rows or Columns in Pandas Dataframe Based on Values Sorting is a fundamental operation when working with data in Pandas. Whether you need to arrange rows in ascending or descending order or reorder columns based on values, Pandas provides powerful functions to make sorting easy and efficient. In this article, we'll explore different ways to sort rows
4 min read
Reorder Columns in a Specific Order Using Python Polars Polars is a powerful DataFrame library in Rust and Python that is known for its speed and efficiency. It's designed to handle large datasets with ease, making it an excellent choice for data analysis and manipulation. One common task in data manipulation is reordering the columns of a data frame. Th
3 min read