gpt4 book ai didi

java - 列排序数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:54:33 24 4
gpt4 key购买 nike

我想对多维数组进行列排序。我有代码设置,但它没有显示正确的结果...

排序前的例子:

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;

}

关于java - 列排序数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29890038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com