第八章第二十七题(列排序)(column sorting)
-
*8.27(行排序)用下面的方法实现一个二维数组中的列排序,返回一个新的数组,并且原数组保持不变。
public static double[][] sortColumns(double[][] m)
编写一个测试程序,提示用户输入一个3×3的double类型值的矩阵。显示一个新的每列排好序的矩阵,下面是一个运行示例:
Enter a 3-by-3 matrix row by row:
0.15 0.375 0.875
0.55 0.005 0.225
0.30 0.12 0.4
The column-sorted array is
0.15 0.005 0.225
0.3 0.12 0.4
0.55 0.375 0.875
*8.27(column sorting)Use the following method to sort the columns in a two-dimensional array, return a new array, and the original array remains unchanged.
public static double[][] sortColumns(double[][] m)
Write a test program to prompt the user to input a matrix of 3 × 3 double type values. Show a new ordered matrix for each column. Here is a running example:
Enter a 3-by-3 matrix row by row:
0.15 0.375 0.875
0.55 0.005 0.225
0.30 0.12 0.4
The column-sorted array is
0.15 0.005 0.225
0.3 0.12 0.4
0.55 0.375 0.875 -
参考代码:
package chapter08; import java.util.Scanner; public class Code_27 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a 3-by-3 matrix row by row:"); double[][] matrix = new double[3][3]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { matrix[i][j] = input.nextDouble(); } } double[][] m=sortColumn(matrix); System.out.println("The column-sorted array is"); int count=0; for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) { System.out.print(m[i][j]+" "); count++; } if (count%3==0) System.out.println(); } } public static double[][] sortColumn(double[][] m) { double temp=0; for (int j = 0; j < m[0].length; j++) { for (int k=0;k<m.length-1;k++) { for (int i = 0; i < m.length - 1 - k; i++) { if (m[i][j] > m[i + 1][j]) { temp = m[i][j]; m[i][j] = m[i + 1][j]; m[i + 1][j] = temp; } } } } return m; } }
-
结果显示:
Enter a 3-by-3 matrix row by row: 0.15 0.375 0.875 0.55 0.005 0.225 0.30 0.12 0.4 The column-sorted array is 0.15 0.005 0.225 0.3 0.12 0.4 0.55 0.375 0.875 Process finished with exit code 0