From c921ef693253c53b57660dc6da4ee9cbf467d0e7 Mon Sep 17 00:00:00 2001 From: Ritesh Maurya <31176772+MauryaRitesh@users.noreply.github.com> Date: Fri, 15 Oct 2021 11:08:39 +0530 Subject: [PATCH] Create Matrix_Sort.py Added a python3 program to sort a given matrix. --- matrix_sort.py | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 matrix_sort.py diff --git a/matrix_sort.py b/matrix_sort.py new file mode 100644 index 0000000..554f017 --- /dev/null +++ b/matrix_sort.py @@ -0,0 +1,49 @@ +# Python3 program to sort a given matrix + +SIZE = 10 + +def sortMat(mat, n) : + + # Temporary matrix of size n^2 + temp = [0] * (n * n) + k = 0 + + # Copy the elements of the matrix into temp[] + for i in range(0, n) : + for j in range(0, n) : + temp[k] = mat[i][j] + k += 1 + + # sort temp[] + temp.sort() + + # copy the elements of temp[] into mat[][] + k = 0 + + for i in range(0, n) : + for j in range(0, n) : + mat[i][j] = temp[k] + k += 1 + +def printMat(mat, n) : + + for i in range(0, n) : + for j in range( 0, n ) : + print(mat[i][j] , end = " ") + + print() + + +# Test Case +mat = [ [ 5, 4, 7 ], + [ 1, 3, 8 ], + [ 2, 9, 6 ] ] +n = 3 + +print( "Given Matrix:") +printMat(mat, n) + +sortMat(mat, n) + +print("\nSorted Matrix: ") +printMat(mat, n)