📌  相关文章
📜  Java程序对矩阵按行和按列进行排序

📅  最后修改于: 2022-05-13 01:54:58.215000             🧑  作者: Mango

Java程序对矩阵按行和按列进行排序

给定anxn矩阵。问题是按行和按列对矩阵进行排序。
例子:

Input : mat[][] = { {4, 1, 3},
                    {9, 6, 8},
                    {5, 2, 7} }
Output : 1 3 4
         2 5 7
         6 8 9

Input : mat[][] = { {12, 7, 1, 8},
                    {20, 9, 11, 2},
                    {15, 4, 5, 13},
                    {3, 18, 10, 6} } 
Output : 1 5 8 12
         2 6 10 15
         3 7 11 18
         4 9 13 20

方法:以下是步骤:

  1. 对矩阵的每一行进行排序。
  2. 获取矩阵的转置。
  3. 再次对矩阵的每一行进行排序。
  4. 再次获得矩阵的转置。

获取矩阵转置的算法:

for (int i = 0; i < n; i++) {
    for (int j = i + 1; i < n; i++) {
        int temp = mat[i][j];
        mat[i][j] = mat[j][i];
        mat[j][i] = temp;
    }
}
Java
// Java implementation to sort the 
// matrix row-wise and column-wise
import java.util.Arrays;
  
class GFG
{
    static final int MAX_SIZE=10;
      
    // function to sort each row of the matrix
    static void sortByRow(int mat[][], int n)
    {
        for (int i = 0; i < n; i++)
      
            // sorting row number 'i'
            Arrays.sort(mat[i]);
    }
      
    // function to find transpose of the matrix
    static void transpose(int mat[][], int n)
    {
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++) 
                {
                // swapping element at index (i, j) 
                // by element at index (j, i)
                int temp=mat[i][j];
                mat[i][j]=mat[j][i];
                mat[j][i]=temp;
                }
    }
      
    // function to sort the matrix row-wise
    // and column-wise
    static void sortMatRowAndColWise(int mat[][],int n)
    {
        // sort rows of mat[][]
        sortByRow(mat, n);
      
        // get transpose of mat[][]
        transpose(mat, n);
      
        // again sort rows of mat[][]
        sortByRow(mat, n);
      
        // again get transpose of mat[][]
        transpose(mat, n);
    }
      
    // function to print the matrix
    static void printMat(int mat[][], int n)
    {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                System.out.print(mat[i][j] + " ");
            System.out.println();
        }
    } 
      
    // Driver code 
    public static void main (String[] args)
    {
        int mat[][] = { { 4, 1, 3 },
                        { 9, 6, 8 },
                        { 5, 2, 7 } };
        int n = 3;
      
        System.out.print("Original Matrix:
");
        printMat(mat, n);
      
        sortMatRowAndColWise(mat, n);
      
        System.out.print("
Matrix After Sorting:
");
        printMat(mat, n);
    }
}
  
// This code is contributed by Anant Agarwal.


输出:

Original Matrix:
4 1 3
9 6 8
5 2 7

Matrix After Sorting:
1 3 4
2 5 7
6 8 9

时间复杂度: O(n 2 log 2 n)。
辅助空间:O(1)。
有关详细信息,请参阅有关按行和按列对矩阵进行排序的完整文章!