假设用户总是输入一个3×3,当你输入用户只能储存阵列不同,因此更容易进行排序。根据列而不是行存储矩阵。排序列
Scanner scan = new Scanner(System.in);
int[] col1 = new int[3];
int[] col2 = new int[3];
int[] col3 = new int[3];
for (int i=0; i<3; i++){ //Store based on column not row
col1[i] = scan.nextInt();
col2[i] = scan.nextInt();
col3[i] = scan.nextInt();
}
int[][] matrix = new int[3][3];
matrix[0] = col1;
matrix[1] = col2;
matrix[2] = col3;
for (int i=0; i<3; i++){ //Sort columns
Arrays.sort(matrix[i]);
}
//The following code is used to print your array properly by rows instead of columns
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
System.out.print(matrix[j][i]+" ");
}
System.out.println();
}
你之后,你可以转置矩阵回按行存储,以便更容易打印,如果你想:你可以做这样的事情。
如果你想有用户设置的矩阵的大小,使其动态,你可以做这样的事情:
Scanner scan = new Scanner(System.in);
int N = 3; //Size of matrix, You can have user input this as well.
int[][] matrix = new int[N][N];
for (int n=0; n<N; n++){ //Initialize Columns
for (int column=0; column<N; column++){
matrix[column][n] = scan.nextInt(); //Store based on column
}
}
for (int i=0; i<N; i++){ //Sort columns
Arrays.sort(matrix[i]);
}
//The following code is used to print your array properly by rows instead of columns
for (int i=0; i<N; i++){
for (int j=0; j<N; j++){
System.out.print(matrix[j][i]+" ");
}
System.out.println();
}
通过柱排序表明数据在逻辑上通过柱分组,不按行。所以最简单的方法是以列方式填充而不是按行方式(只有你的思路说第一个维度是行,它也可以是列)。你能告诉我们关于你存储的数据的一些信息吗? – Turing85