我是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/