Column Sort of a Matrix in Python


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[0])
      res = [[0] * 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))

Input

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

Output

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

Updated on: 22-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements