Column Sort of a Matrix in Python

PythonServer Side ProgrammingProgramming

Suppose we have a matrix, we have to sort each of the columns in ascending order.

So, if the input is like

 11 21 31 6 6 4 1 11 8

then the output will be

 1 6 4 6 11 8 11 21 31

To solve this, we will follow these steps −

• R := row count of matrix, C := column count of matrix
• res := matrix of same size as given matrix and fill with 0
• for col in range 0 to C, do
• values := take the elements as a vector of matrix[col]
• for row in range 0 to R, do
• res[row, col] := delete last element from values
• return res

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution:
def solve(self, matrix):
R = len(matrix)
C = len(matrix)
res = [ * C for _ in range(R)]
for col in range(C):
values = [r[col] for r in matrix]
values.sort(reverse=True)
for row in range(R):
res[row][col] = values.pop()
return res
ob = Solution()
matrix = [[11, 21, 31],[6, 6, 4],[1, 11, 8]]
print(ob.solve(matrix))

[[11, 21, 31],
[6, 6, 4],
[1, 11, 8]]

Output

[[1, 6, 4],[6, 11, 8],[11, 21, 31]]