我想对多维数组进行列排序。我已经设置了代码,但是没有显示正确的结果...
排序前的示例:
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
请告诉我我做错了!
谢谢!
您的排序算法不是排序-它在做奇怪的事情。
这是一个等效的气泡排序演示。
public static double[][] sortColumns(double[][] m) {
for (int col = 0; col < m[0].length; col++) {
// Have we swapped one on this pass?
boolean swapped;
do {
swapped = false;
for (int row = 0; row < m.length - 1; row++) {
// Should these be swapped?
if (m[row][col] > m[row + 1][col]) {
// Swap this one with the next.
double temp = m[row][col];
m[row][col] = m[row + 1][col];
m[row + 1][col] = temp;
// We swapped! Remember to run through again.
swapped = true;
}
}
} while (swapped);
}
return m;
}
尽管更好的选择是将每一列复制到单独的数组中,然后对其进行排序并放回原位-至少这样一来,您就无需实现自己的排序算法。
public static double[][] sortColumnsProperly(double[][] m) {
// Sort each colum.
for (int col = 0; col < m[0].length; col++) {
// Pull the column out.
double[] thisCol = new double[m.length];
for (int i = 0; i < m.length; i++) {
thisCol[i] = m[i][col];
}
// Sort it.
Arrays.sort(thisCol);
// Push it back in.
for (int i = 0; i < m.length; i++) {
m[i][col] = thisCol[i];
}
}
return m;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句