Answer to Question #237253 in Python for kaavya

Question #237253

Ordered Matrix

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

Sample Input 1

3 3

1 20 3

30 10 2

5 11 15

Sample Output 1

1 2 3

5 10 11

15 20 30

Sample Input 2

2 5

-50 20 3 25 -20

88 17 38 72 -10

Sample Output 2

-50 -20 -10 3 17

20 25 38 72 88


1
Expert's answer
2021-09-16T09:27:42-0400
def read_matrix():
    s = input()
    m = int(s.split()[0])
    n = int(s.split()[1])
    M = []
    for i in range(m):
        s = input()
        row = [int(x) for x in s.split()]
        M.append(row)
    return M

def print_matrix(M):
    for row in M:
        for x in row:
            print(x, end=' ')
        print()

def sort_matrix(M):
    m = len(M)
    n = len(M[0])

    def indx2ij(indx):
        i = indx // n
        j = indx % n
        return (i, j)
    
    for indx in range(m*n-1):
        i_min, j_min = indx2ij(indx)
        for indx2 in range(indx+1, m*n):
            i, j = indx2ij(indx2)
            if M[i][j] < M[i_min][j_min]:
                i_min, j_min = i, j
        i, j = indx2ij(indx)
        M[i][j], M[i_min][j_min] = M[i_min][j_min], M[i][j]

def main():
    M = read_matrix()
    sort_matrix(M)
    print()
    print_matrix(M)

if __name__ == '__main__':
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS