Given a M x N matrix, write a program to print the matrix after ordering all the elements of the matrix in increasing order.Input
The first line of input will contain two space-separated integers, denoting the M and N.
The next M following lines will contain N space-separated integers, denoting the elements of each list.Output
The output should be M lines containing the ordered matrix.
Note: There is a space at the end of each line.Explanation
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
By ordering all the elements of the matrix in increasing order, the ordered matrix should be
1 2 3
5 10 11
15 20 30
sizes = [int(i) for i in input().split()]
M = sizes[0]
N = sizes[1]
matrix = []
for i in range(M):
row = [int(j) for j in input().split()]
if len(row) != N:
raise ValueError('Length of row is not N')
matrix.append(row)
vector = []
for i in range(M):
for j in range(N):
vector.append(matrix[i][j])
vector.sort()
for i in range(M):
for j in range(N):
matrix[i][j] = vector[0]
vector = vector[1:]
for i in range(M):
for j in range(N):
print(matrix[i][j], end=' ')
print()
Comments
Leave a comment