用下面的方法实现一个二维数组中的列排序,返回新数组,且原数组保持不变:
public static double[][] sortColumns(double[][] m)
编写一个测试程序,提示用户输入一个3 * 3的double型矩阵,显示一个排好的矩阵。
package pack2;
import java.util.Arrays;
import java.util.Scanner;
public class SortColumns {
public static void main(String[] args) {
showSortColumns();
}
// 0.15 0.875 0.375
// 0.55 0.005 0.225
// 0.30 0.12 0.4
public static void showSortColumns() {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter the length of a matrix: ");
int length = input.nextInt();
double[][] m = new double[length][length];
System.out.println("Enter a " + length + "-by-" + length +
" matrix row by row: ");
inputData(input, m);
System.out.println("\nThe column-sorted array is ");
printMatrix(sortColumns(m));
}
}
/**接收数据输入*/
public static void inputData(Scanner input, double[][] m) {
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
m[i][j] = input.nextDouble();
}
/**列排序*/
public static double[][] sortColumns(double[][] m) {
double[][] temp = new double[m.length][m[0].length]; //临时数组
for (int i = 0; i < temp.length; i++)
for (int j = 0; j < temp.length; j++)
temp[i][j] = m[j][i]; //矩阵的转置元素赋给temp数组
for (int i = 0; i < temp.length; i++)
Arrays.sort(temp[i]); //执行每行排序
return temp;
}
/**打印矩阵*/
public static void printMatrix(double[][] m) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m.length; j++)
System.out.printf(" " + m[j][i]); //打印j列i行
System.out.println();
}
}
}