📜  对给定的矩阵进行排序 |内存高效的方法

📅  最后修改于: 2021-09-03 03:47:45             🧑  作者: Mango

给定一个NM列的矩阵,任务是按照严格的顺序对矩阵进行排序,即每行按递增顺序排序,并且每行的第一个元素大于前一行的第一个元素。

例子:

Input: M[][] = { {5, 4, 7}, 
                 {1, 3, 8}, 
                 {2, 9, 6} }
Output: 1 2 3
        4 5 6
        7 8 9
Explanation:
Please refer above image

Input: M[][] = { {5, 4, 7},
                 {1, 3, 8} }
Output: 1 3 4
        5 7 8

方法:想法是将 2D-Array 视为 1D-Array 来对矩阵进行排序,而不使用额外的空间。这也可以在以下示例的帮助下进行解释。

例如:

There is a 2*2 Matrix with 4 elements,
The idea is to treat the elements of the matrix
as 1D Array of 4 elements.
1 2
3 4

As In the given matrix each element can be accessed as -
1st Element - 0th Row, 0th Col
2nd Element - 0th Row, 1st Col
3rd Element - 1st Row, 0th Col
4th Element - 1st Row, 1st Col 

因此,对于访问矩阵的i元素,关系可以定义为:

算法:

  • 通过找到在2D-阵列的行数和在阵列中的每个行中的元件的长度找到行(比如)和在矩阵的列(比如COLS)的数量。
  • 迭代矩阵的每个元素,从 0 到元素数(行 * 列)。
  • 使用上述公式为每个元素找到矩阵中元素的适当位置。
  • 将每个元素与矩阵中的下一个元素(对于行中的最后一个元素,下一个元素将是下一行的第一个元素)进行比较,如果下一个元素是,则减去这些元素。

举例说明:

I J Comparison Elements Matrix Comments
0 0 (0, 0) & (0, 1) 5 6
1 4 8
No Swap
0 1 (0, 1) & (0, 2) 5 6 7 
1 4 8
No Swap
0 2 (0, 2) & (1, 0) 5 6 1 
7 4 8
Swapped
0 3 (1, 0) & (1, 1) 5 6 1 
4 7 8
Swapped
0 4 (1, 1) & (1, 2) 5 6 1 
4 7 8
No Swap
1 0 (0, 0) & (0, 1) 5 6
4 7 8
No Swap
1 1 (0, 1) & (0, 2) 5 1 6 
4 7 8
Swapped
1 2 (0, 2) & (1, 0) 5 1 4 
6 7 8
Swapped
1 3 (1, 0) & (1, 1) 5 1 4 
6 7 8
No Swap
1 4 (1, 1) & (1, 2) 5 1 4 
4 7 8
No Swap
2 0 (0, 0) & (0, 1) 1 5
6 7 8
Swapped
2 1 (0, 1) & (0, 2) 1 4 5 
6 7 8
Swapped
2 2 (0, 2) & (1, 0) 1 4 5 
6 7 8
No Swap
2 3 (1, 0) & (1, 1) 5 1 4 
6 7 8
No Swap
2 4 (1, 1) & (1, 2) 5 1 4 
4 7 8
No Swap

下面是上述方法的实现:

C++
// C++ implementation to sort
// the given matrix in strict order
#include 
using namespace std;
#define N 3
#define M 3
 
// Function to sort the matrix
void sortMat(int data[N][M], int row, int col)
{
 
    // Number of elements in matrix
    int size = row * col;
 
    // Loop to sort the matrix
    // using Bubble Sort
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size - 1; j++)
        {
 
            // Condition to check
            // if the Adjacent elements
            if (data[j / col][j % col] > data[(j + 1)
                / col][(j + 1) % col])
            {
 
                // Swap if previous value is greater
                int temp = data[j / col][j % col];
                data[j / col][j % col] = data[(j + 1)
                    / col][(j + 1) % col];
                data[(j + 1) / col][(j + 1) % col] = temp;
            }
        }
    }
}
 
void printMat(int mat[N][M], int row, int col)
{
 
    // Loop to print the matrix
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    int mat[N][M] = { { 5, 4, 7 },
                        { 1, 3, 8 },
                        { 2, 9, 6 } };
         
    int row = N;
    int col = M;
 
    // Function call to sort
    sortMat(mat, row, col);
 
    // Function call to
    // print matrix
    printMat(mat, row, col);
    return 0;
}
 
// This code is contributed by 29AjayKumar


Java
// Java implementation to sort
// the given matrix in strict order
class GFG
{
    // Function to sort the matrix
    static void sortMat(int[][] data, int row, int col)
    {
 
        // Number of elements in matrix
        int size = row * col;
 
        // Loop to sort the matrix
        // using Bubble Sort
        for (int i = 0; i < size; i++)
        {
            for (int j = 0; j < size - 1; j++)
            {
 
                // Condition to check
                // if the Adjacent elements
                if (data[j / col][j % col] > data[(j + 1)
                    / col][(j + 1) % col])
                {
 
                    // Swap if previous value is greater
                    int temp = data[j / col][j % col];
                    data[j / col][j % col] = data[(j + 1)
                        / col][(j + 1) % col];
                    data[(j + 1) / col][(j + 1) % col] = temp;
                }
            }
        }
    }
 
    static void printMat(int[][] mat, int row, int col)
    {
 
        // Loop to print the matrix
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                System.out.print(mat[i][j] + " ");
            }
            System.out.println();
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
         
        int[][] mat = { { 5, 4, 7 },
                        { 1, 3, 8 },
                        { 2, 9, 6 } };
         
        int row = mat.length;
        int col = mat[0].length;
 
        // Function call to sort
        sortMat(mat, row, col);
 
        // Function call to
        // print matrix
        printMat(mat, row, col);
    }
}
 
// This code is contributed by PrinciRaj1992


Python3
# Python3 implementation to sort
# the given matrix in strict order
 
# Function to sort the matrix
def sortMat(data, row, col):
     
    # Number of elements in matrix
    size = row * col
     
    # Loop to sort the matrix
    # using Bubble Sort
    for i in range(0, size):
        for j in range(0, size-1):
             
            # Condition to check
            # if the Adjacent elements
            if ( data[j//col][j % col] >\
                data[(j + 1)//col][(j + 1)% col] ):
                 
                # Swap if previous value is greater
                temp = data[j//col][j % col]
                data[j//col][j % col] =\
                    data[(j + 1)//col][(j + 1)% col]
                data[(j + 1)//col][(j + 1)% col] =\
                                 temp
 
def printMat(mat, row, col):
     
    # Loop to print the matrix
    for i in range(row):
        for j in range(col):
            print(mat[i][j], end =" ")
        print()
 
# Driver Code
if __name__ == "__main__":
    mat = [ [5, 4, 7],
            [1, 3, 8],
            [2, 9, 6] ]
    row = len(mat)
    col = len(mat[0])
     
    # Function call to sort
    sortMat(mat, row, col)
     
    # Function call to
    # print matrix
    printMat(mat, row, col)


C#
// C# implementation to sort
// the given matrix in strict order
using System;
 
class GFG
{
    // Function to sort the matrix
    static void sortMat(int[,] data, int row, int col)
    {
  
        // Number of elements in matrix
        int size = row * col;
  
        // Loop to sort the matrix
        // using Bubble Sort
        for (int i = 0; i < size; i++)
        {
            for (int j = 0; j < size - 1; j++)
            {
  
                // Condition to check
                // if the Adjacent elements
                if (data[j / col,j % col] > data[(j + 1)
                    / col,(j + 1) % col])
                {
  
                    // Swap if previous value is greater
                    int temp = data[j / col,j % col];
                    data[j / col,j % col] = data[(j + 1)
                        / col,(j + 1) % col];
                    data[(j + 1) / col,(j + 1) % col] = temp;
                }
            }
        }
    }
  
    static void printMat(int[,] mat, int row, int col)
    {
  
        // Loop to print the matrix
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                Console.Write(mat[i,j] + " ");
            }
            Console.WriteLine();
        }
    }
  
    // Driver Code
    public static void Main(String[] args)
    {
          
        int[,] mat = { { 5, 4, 7 },
                        { 1, 3, 8 },
                        { 2, 9, 6 } };
          
        int row = mat.GetLength(0);
        int col = mat.GetLength(1);
  
        // Function call to sort
        sortMat(mat, row, col);
  
        // Function call to
        // print matrix
        printMat(mat, row, col);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
1 2 3 
4 5 6 
7 8 9

性能分析:

  • 时间复杂度:在给定的方法中,我们通过使用冒泡排序考虑一维数组中的元素来对矩阵中的元素进行排序,因此整体复杂度将为O(N * M>)
  • 空间复杂度:在给定的方法中,没有使用额外的空间,所以整体空间复杂度为O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live