Given a M x N matrix, write a program to print the matrix after ordering all the elements of the matrix in increasing order.For example, if the given M is 3 and N is 3, read the inputs in the next three lines if the numbers given in the next three lines are the following.
1 20 3
30 10 2
5 11 15
def ReadMatrix(m, n):
M = []
for i in range(m):
s = input()
s = s.split()
row = []
for j in range(n):
row.append(int(s[j]))
M.append(row)
return M
def SortMatrix(M):
m = len(M)
n = len(M[0])
L = []
for row in M:
L += row
L.sort()
M = []
for i in range(m):
M.append(L[n*i:n*(i+1)])
return M
def PrintMatrix(M):
for row in M:
for x in row:
print(x, end=' ')
print()
def main():
m = int(input())
n = int(input())
M = ReadMatrix(m, n)
print()
M = SortMatrix(M)
PrintMatrix(M)
if __name__ == '__main__':
main()
Comments
Leave a comment