📌  相关文章
📜  用于对给定矩阵进行排序的Java程序

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

用于对给定矩阵进行排序的Java程序

给定anxn矩阵。问题是按照严格的顺序对给定的矩阵进行排序。这里严格的顺序意味着矩阵的排序方式使得一行中的所有元素都按升序排序,对于行'i',其中1 <= i <= n-1,行'i'的第一个元素更大大于或等于“i-1”行的最后一个元素。
例子:

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

方法:创建一个大小为 n^2 的temp[]数组。从第一行开始,将给定矩阵的元素一个接一个地复制到 temp[] 中。排序 temp[]。现在将 temp[] 的元素一一复制回给定的矩阵。

Java
// Java implementation to 
// sort the given matrix
import java.io.*;
import java.util.*;
  
class GFG {
      
    static int SIZE = 10;
  
    // function to sort the given matrix
    static void sortMat(int mat[][], int n)
    {
        // temporary matrix of size n^2
        int temp[] = new int[n * n];
        int k = 0;
      
        // copy the elements of matrix 
        // one by one into temp[]
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                temp[k++] = mat[i][j];
      
        // sort temp[]
        Arrays.sort(temp);
          
        // copy the elements of temp[]
        // one by one in mat[][]
        k = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                mat[i][j] = temp[k++];
    }
      
    // function to print the given 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 program to test above
    public static void main(String args[])
    {
        int mat[][] = { { 5, 4, 7 },
                        { 1, 3, 8 },
                        { 2, 9, 6 } };
        int n = 3;
      
        System.out.println("Original Matrix:");
        printMat(mat, n);
      
        sortMat(mat, n);
      
        System.out.println("Matrix After Sorting:");
        printMat(mat, n);
      
    }
}
  
// This code is contributed by Nikita Tiwari.


输出:

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

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

时间复杂度:O(n 2 log 2 n)。
辅助空间:O(n 2 )。

有关详细信息,请参阅有关对给定矩阵进行排序的完整文章!