📌  相关文章
📜  跨行对二维数组进行排序的Java程序

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

跨行对二维数组进行排序的Java程序

该程序用于对二维数组进行跨行排序。我们将使用向量的概念对每一行进行排序。

向量

我们将在此使用的函数:



1. removeAll() Java.util.vector.removeAll(Collection col) 方法用于从向量中移除指定集合中存在的所有元素。

句法:

Vector.removeAll(Vector) 

2. Collections.sort():该方法用于对向量进行排序。

句法:

Collections.sort(Vector)

3.添加(): 这会将向量中的元素相加。

句法:

Vector.add(value)

4.获取(): 此方法将获取存储在特定索引处的 Vector 元素。

句法:

Vector.get(element);

算法:

  1. 逐行遍历每一行。
  2. 在向量 v 中添加第 1 行的元素。
  3. 对向量进行排序。
  4. 将排序的元素从向量推回到行。
  5. 通过删除所有元素来清空向量以进行新排序。
  6. 重复上述步骤,直到完成所有行。

执行:

例子

Java
// Java Program to Sort the 2D array Across Rows
 
// Importing required libraries
import java.io.*;
import java.lang.*;
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws java.lang.Exception
    {
 
        // Custom input 2D matrix
        int[][] arr = { { 1, 8, 4, 7, 3 },
                        { 8, 3, 1, 7, 5 },
                        { 6, 2, 0, 7, 1 },
                        { 2, 6, 4, 1, 9 } };
 
        // Display message only
        System.out.println("Matrix without sorting \n");
 
        // Print and display the matrix before sorting
        // using nested for loops
        for (int i = 0; i < 4; i++) {
 
            for (int j = 0; j < 5; j++) {
                // Printing the matrix elements
                System.out.print(arr[i][j] + " ");
            }
 
            // New line as we are finished with one row
            System.out.println();
        }
 
        // New line for better readability
        System.out.println();
 
        // Creating an object of Vector class
        Vector v = new Vector<>();
 
        for (int i = 0; i < 4; i++) {
 
            for (int j = 0; j < 5; j++) {
                // Adding elements of row in vector
                v.add(arr[i][j]);
            }
 
            // Elements in vector gets sorted
            Collections.sort(v);
            for (int j = 0; j < 5; j++) {
 
                // Sorted elements are pushed back from
                // vector to row
                arr[i][j] = v.get(j);
            }
 
            // Elements are removed from vector for fresh
            // sorting
            v.removeAll(v);
        }
 
        // Display message only
        System.out.println("Matrix after sorting \n");
 
        // Print and display the matrix after sorting
        // using nested for loops
        for (int i = 0; i < 4; i++) {
 
            for (int j = 0; j < 5; j++) {
 
                // Printing the matrix elements
                System.out.print(arr[i][j] + " ");
            }
 
            // New line as we are finished with one row
            System.out.println();
        }
    }
}


输出
Matrix without sorting 

1 8 4 7 3 
8 3 1 7 5 
6 2 0 7 1 
2 6 4 1 9 

Matrix after sorting 

1 3 4 7 8 
1 3 5 7 8 
0 1 2 6 7 
1 2 4 6 9