Python Program to Sort the given matrix
Last Updated :
14 Apr, 2023
Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, where 1 <= i <= n-1, first element of row 'i' is greater than or equal to the last element of row 'i-1'.
Examples:
Input : mat[][] = { {5, 4, 7},
{1, 3, 8},
{2, 9, 6} }
Output : 1 2 3
4 5 6
7 8 9
Approach: Create a temp[] array of size n^2. Starting with the first row one by one copy the elements of the given matrix into temp[]. Sort temp[]. Now one by one copy the elements of temp[] back to the given matrix.
Python3
# Python3 implementation to sort
# the given matrix
SIZE = 10
# Function to sort the given matrix
def sortMat(mat, n) :
# Temporary matrix of size n^2
temp = [0] * (n * n)
k = 0
# Copy the elements of matrix
# one by one into temp[]
for i in range(0, n) :
for j in range(0, n) :
temp[k] = mat[i][j]
k += 1
# sort temp[]
temp.sort()
# copy the elements of temp[]
# one by one in mat[][]
k = 0
for i in range(0, n) :
for j in range(0, n) :
mat[i][j] = temp[k]
k += 1
# Function to print the given matrix
def printMat(mat, n) :
for i in range(0, n) :
for j in range( 0, n ) :
print(mat[i][j] , end = " ")
print(" ")
# Driver program to test above
mat = [ [ 5, 4, 7 ],
[ 1, 3, 8 ],
[ 2, 9, 6 ] ]
n = 3
print( "Original Matrix:")
printMat(mat, n)
sortMat(mat, n)
print("Matrix After Sorting:")
printMat(mat, n)
# This code is contributed by Nikita Tiwari.
OutputOriginal Matrix:
5 4 7
1 3 8
2 9 6
Matrix After Sorting:
1 2 3
4 5 6
7 8 9
Time Complexity: O(n2log2n).
Auxiliary Space: O(n2).
To sort the matrix in the required strict order, we can use a different approach. One possibility is to flatten the matrix into a single list, sort the list, and then reshape the list into the original matrix shape.
Here is an example of how this can be done:
Python3
import numpy as np
mat = [[5, 4, 7],
[1, 3, 8],
[2, 9, 6]]
# flatten the matrix into a single list
flat_list = [item for sublist in mat for item in sublist]
# sort the list
flat_list.sort()
# reshape the list into the original matrix shape
mat = np.array(flat_list).reshape((3, 3))
# print the sorted matrix
for row in mat:
print(row)
This will print the following matrix:
[1 2 3]
[4 5 6]
[7 8 9]
Time complexity: O(N * log N), where N is the number of elements in the matrix.
Auxiliary space: O(N), as it requires an additional list to store the flattened matrix.
Please refer complete article on Sort the given matrix for more details!
Approach#3: Using heapq
Another way to sort the matrix is to use a heap. We can create a min-heap and then extract the minimum element repeatedly to create a sorted list, which can then be reshaped back into a matrix.
Algorithm
1. Create a min-heap and insert all elements of the matrix into it.
2. Extract the minimum element from the heap repeatedly to create a sorted list.
3. Reshape the sorted list back into a matrix.
Python3
import heapq
def sort_matrix(mat):
# Step 1: Create a min-heap and insert all elements of the matrix into it.
heap = []
for row in mat:
for num in row:
heapq.heappush(heap, num)
# Step 2: Extract the minimum element from the heap repeatedly to create a sorted list.
sorted_list = []
while heap:
sorted_list.append(heapq.heappop(heap))
# Step 3: Reshape the sorted list back into a matrix.
n_rows = len(mat)
n_cols = len(mat[0])
sorted_mat = [sorted_list[i:i+n_cols] for i in range(0, len(sorted_list), n_cols)]
return sorted_mat
# Example usage:
mat = [[5, 4, 7], [1, 3, 8], [2, 9, 6]]
sorted_mat = sort_matrix(mat)
for row in sorted_mat:
print(row)
Output[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Time Complexity: O(n log n), where n is the total number of elements in the matrix. This is because inserting n elements into the heap takes O(n log n) time, and extracting n elements from the heap also takes O(n log n) time.
Space Complexity: O(n), where n is the total number
Similar Reads
Python Program to Sort a String Sorting strings in Python is a common and important task, whether we need to organize letters alphabetically or systematically handle text data. In this article, we will explore different methods to sort a string starting from the most efficient to the least.Using sorted with join()sorted() function
2 min read
Python Program to Sort the matrix row-wise and column-wise 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
4 min read
Python program to sort matrix based upon sum of rows Given a Matrix, perform sort based upon the sum of rows. Input : test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Output : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 3 < 9 < 11 < 14. Sorted sum. Input : test_list = [[4, 5], [2, 5, 7], [4, 6, 1]] Output : [[4, 5], [4, 6, 1], [2,
6 min read
Python program to Sort Matrix by Maximum Row element Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
4 min read
Python - Sort Matrix by Palindrome count Given a String Matrix of N characters, sort each row by the count of the palindromic string in it. Input : test_list = [["nitin", "meem", "geeks"], ["peep"], ["gfg", "is", "best"], ["sees", "level", "mom", "noon"]] Output : [['peep'], ['gfg', 'is', 'best'], ['nitin', 'meem', 'geeks'], ['sees', 'leve
8 min read
Python program to a Sort Matrix by index-value equality count Given a Matrix, the task is to write a Python program that can sort its rows or columns on a measure of the number of values equal to its index number. For each row or column, count occurrences of equality of index number with value. After computation of this count for each row or column, sort the m
6 min read
Python Program to Sort Matrix by Sliced Row and Column Summation Given a Matrix and a range of indices, the task is to write a python program that can sort a matrix on the basis of the sum of only given range of indices of each row and column i.e. the rows and columns are to sliced from a given start to end index, further, matrix are sorted using only those slice
8 min read
Python - Sort Matrix by Maximum String Length Given a matrix, perform row sort basis on the maximum length of the string in it. Input : test_list = [['gfg', 'best'], ['geeksforgeeks'], ['cs', 'rocks'], ['gfg', 'cs']] Output : [['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks'], ['geeksforgeeks']] Explanation : 3 < 4 < 5 < 13, maximum leng
3 min read
Python Program to sort rows of a matrix by custom element count Given Matrix, the following program shows how to sort rows of a matrix by the count of presence of numbers from a specified list. Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7] Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]] Explanation : 0 < 1 = 1 < 3 i
5 min read