javascript - 如何对二维整数数组进行升序和降序排序

标签 javascript

我是java技术的新手,我在处理2D数组时面临问题。我尝试了很多逻辑,它们要么基于,要么基于任何其他标准。我的项目中有一个这样的案例需要解决

我有一个a[3][3]矩阵 就像

9 8 7
4 3 2
0 5 4

我的标准是我想要矩阵

0 2 3
4 4 5
7 8 9

以及

9 8 7  
5 4 4
3 2 0

我的Java代码

 public class MatrixExample {

     Scanner scan;

     Integer matrix[][];

     int row,column;

 void create() {

     scan=new Scanner(System.in);

     System.out.println("Matrix creation");

     System.out.println("\n Enter Rows");

     row=Integer.parseInt(scan.nextLine());

     System.out.println("\n Enetr columns");

     column=Integer.parseInt(scan.nextLine());

     matrix=new Integer[row][column];

     System.out.println("Enter the data");


     for(int i=0;i<row;i++) {

        for(int j=0;j<column;j++) {

            matrix[i][j]=scan.nextInt();

        }

    }

}

void display() {

    for(int i=0;i<row;i++) {

        for(int j=0;j<column;j++) {

            System.out.print("\t" +matrix[i][j]);

        }



        System.out.println();

    }

}
void sortmatrix() {
     Arrays.sort(matrix, new Comparator<Integer[]>(){
            @Override
            public int compare(Integer[] o1, Integer[] o2) {
                return o1[0].compareTo(o2[0]);
            } });
    System.out.println("After:");
    for(Integer[] row : matrix) {
        Arrays.sort(row);
        for(Integer num : row) {
            System.out.print(num);
        }
        System.out.println("");
    }

}
public static void main(String []args){
    MatrixExample h= new MatrixExample();
    h.create();
    h.display();
    h.sortmatrix();
 }
}

最佳答案

从概念上讲,当您对行进行排序时,您没有 2D 3x3 矩阵,而是一个包含 9 个值的线性数组。

为了达到预期的结果,输入9个值,对它们进行递增排序并以两种方式输出:

  • 作为 3x3 数组,
  • 作为 3x3 数组,以相反的顺序获取数组元素。

关于javascript - 如何对二维整数数组进行升序和降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32646843/

相关文章:

javascript - 如何使用 jquery/ajax 刷新 div 中的表格内容

javascript - 添加和删​​除类并防止 fadeTo

javascript - jQuery 切换不适用于复选框,div 仍显示 :block

javascript - Ruby on Rails - 动态生成的部分中的 JavaScript

javascript - 在测试中总是先遇到“hook”并且无法修复它

javascript - 在JavaScript中检测苹果的强制幻像横幅

javascript - enzyme 安装 API 问题 : TypeError: Cannot read property 'find' of undefined

javascript - 如何为 Promise.all 参数映射字符串数组?

javascript - 使用发布数据重新加载页面

javascript - Node 库公开具有依赖关系的组件