在本文中,我们将学习一个 python 程序来按行和按列对矩阵进行排序。
假设我们采用了一个输入的 MxM 矩阵。我们现在将使用嵌套的 for 循环对给定的输入矩阵进行逐行和按列排序。
以下是执行所需任务要遵循的算法/步骤。−
以下程序使用嵌套的 for 循环返回给定输入矩阵的按行和按列排序的矩阵 -
# creating a function for sorting each row of matrix row-wise def sortingMatrixByRow(inputMatrix, m): # traversing till the length of rows of a matrix for p in range(m): # Sorting the current row for q in range(m-1): # checking whether the current element is greater than the next element if inputMatrix[p][q] >inputMatrix[p][q + 1]: # swapping the elements using a temporary variable # if the condition is true tempVariable = inputMatrix[p][q] inputMatrix[p][q] = inputMatrix[p][q + 1] inputMatrix[p][q + 1] = tempVariable # creating a function to get the transpose of a matrix # by accepting the input matrix, m values as arguments def transposeMatrix(inputMatrix, m): # traversing through the rows of a matrix for p in range(m): # Traversing from row +1 column to last column for q in range(p + 1, m): # Swapping the element at index (p,q) with (q,p) temp = inputMatrix[p][q] inputMatrix[p][q] = inputMatrix[q][p] inputMatrix[q][p] = temp # creating a function for sorting the matrix rows column-wise def sortMatrixRowandColumn(inputMatrix, m): # sorting the rows of an input matrix by # calling the above defined sortingMatrixByRow() function sortingMatrixByRow(inputMatrix, m) # getting the transpose of an input matrix by # calling the above defined transposeMatrix() function transposeMatrix(inputMatrix, m) # once again sorting the rows of an input matrix by # calling the above defined sortingMatrixByRow() function sortingMatrixByRow(inputMatrix, m) # once again getting the transpose of an input matrix(So we sorted the columns) transposeMatrix(inputMatrix, m) # creating a function to print the matrix def printingMatrix(inputMatrix, rows): # Traversing in the rows of the input matrix for i in range(rows): # Traversing in the columns corresponding to the current row # of the input matrix for j in range(rows): print(inputMatrix[i][j], end=" ") # Printing a new line to separate the rows print() # input matrix inputMatrix = [[2, 6, 5], [1, 9, 8], [7, 3, 10]] # input m value representing 3x3 matrix # (dimensions) m = 3 print("Input Matrix:") # printing the input matrix by calling the above # printingMatrix() function printingMatrix(inputMatrix, m) # calling the above defined sortMatrixRowandColumn() function # by passing the input matrix, m values to it to # sort the matrix row and column-wise sortMatrixRowandColumn(inputMatrix, m) # printing the input matrix after sorting row and column-wise # by calling the above printingMatrix() function print("Input Matrix after sorting row and column-wise:") printingMatrix(inputMatrix, m)
在执行时,上述程序将生成以下输出 -
Input Matrix: 2 6 5 1 9 8 7 3 10 Input Matrix after sorting row and column-wise: 1 5 6 2 7 9 3 8 10
时间复杂度 − O(n^2 log2n)
辅助空间 − O(1)
在本文中,我们学习了如何使用 Python 对给定的矩阵进行行和列排序。此外,我们还学习了如何转置给定的矩阵,以及如何使用嵌套的 for 循环(而不是使用内置的 sort() 方法)按行对矩阵进行排序。