Given a M x N matrix, write a program to print the matrix after ordering all the elements of the matrix in increasing order.
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.
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
Output should be in matrix form
M = int(input("Enter the value of M"))
N = int(input("Enter the value of N"))
w, h = M, N;
matrix = [[0 for x in range(w)] for y in range(h)]
i=0
j=0
while i < M:
while j < N:
matrix[i][j] = int(input("enter number"))
j+=1
i+=1
j=0
matrix.sort()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
for k in range(len(matrix[i]) - j - 1):
if (matrix[i][k] > matrix[i][k + 1]):
t = matrix[i][k]
matrix[i][k] = matrix[i][k + 1]
matrix[i][k + 1] = t
matrix.sort()
k=0
l=0
while k < M:
while l < N:
print(matrix[k][l], sep='', end=' ', flush=True)
l+=1
k+=1
print("\n")
l=0
#matrix.sort(key=lambda x:x[1],reverse=True)
Comments
Leave a comment