我想對多維數組進行列排序。我的代碼設置,但它不是...列對數組進行排序?
示例排序前顯示正確的結果:
6.0 4.0 2.0
4.0 2.0 4.0
1.0 3.0 1.0
例分選後:
1.0 2.0 1.0
4.0 3.0 2.0
6.0 4.0 4.0
這是我的代碼:
import java.util.Scanner;
public class ColumnSorting
{
public static void main(String [] args)
{
run();
}
public static void run()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter the values of your 3x3 matrix: ");
double[][] matrix = new double[3][3];
for (int i = 0; i < matrix.length; i++)
{
for (int k = 0; k < matrix[i].length; k++)
{
matrix[i][k] = input.nextDouble();
}
}
printArrays(matrix);
}
public static void printArrays(double[][] matrix)
{
System.out.println("Before sorting: ");
for (int i = 0; i < matrix.length; i++)
{
for (int k = 0; k <matrix[i].length; k++)
{
System.out.print(matrix[i][k] + " ");
}
System.out.println();
}
double[][] newMatrix = sortColumns(matrix);
System.out.println();
System.out.println("After sorting: ");
for (int i = 0; i < newMatrix.length; i++)
{
for (int j =0; j < newMatrix[i].length; j++)
{
System.out.print(newMatrix[i][j] + " ");
}
System.out.println();
}
}
public static double[][] sortColumns(double[][] m)
{
double min;
double temp;
for (int i = 0; i < 3; i++)
{
min = m[0][i];
for (int k = 0; k < m.length; k++)
{
if (min > m[k][i])
{
temp = min;
m[0][i] = m[k][i];
m[k][i] = temp;
}
}
}
return m;
}
}
這就是我得到:
1.0 3.0 1.0
6.0 4.0 4.0
6.0 4.0 2.0
請告訴我我做錯了什麼!
謝謝!