【发布时间】:2018-06-02 06:11:18
【问题描述】:
我是 java 新手,我正在尝试按列和按行打印从选择排序算法中获得的元素。 未排序矩阵的预期输出可以是行 486 123 147 927 到 456(行)或 258(列) 135(未分类)789 369 提前致谢!由于我是学生,请不要专业的解决方案。
public void sort(boolean byColumn)
{
double[] temp = null;
double placeHolder = 0.0;
int total = 0;
int index = 0;
/* Incrementing the total to use for the length of the temporary array. */
for (int rows = 0; rows < mdArray.length; rows++)
{
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
total++;
}
}
temp = new double[total];
/* This nested for loop converts the indices of mdArray to one long temp array. */
for (int rows = 0; rows < mdArray.length; rows++)
{
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
temp[index] = mdArray[rows][columns];
index++;
}
}
for (int i = 0; i < temp.length; i++) // Sorting the temporary array using selection sort.
{
for (int j = i + 1; j < temp.length; j++)
{
if (temp[j] < temp[i])
{
placeHolder = temp[i];
temp[i] = temp[j];
temp[j] = placeHolder;
}
}
}
index = 0;
if (byColumn) // Sorting the invoking array by column.
{
for (int rows = 0; rows < mdArray.length; rows++) // Puts sorted elements back into mdArray.
{
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
mdArray[rows][columns] = temp[index];
index++;
}
}
for (int rows = 0; rows < mdArray.length; rows++)
{
System.out.println();
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
System.out.print(mdArray[rows][columns] + " ");
}
}
}
else if (!byColumn) // Sorting the invoking by row.
{
for (int columns = 0; columns < mdArray[columns].length; columns++)
{
for (int rows = 0; rows < mdArray.length; rows++)
{
mdArray[columns][rows] = temp[index];
index++;
}
}
for (int rows = 0; rows < mdArray.length; rows++)
{
System.out.println();
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
System.out.print(mdArray[rows][columns] + " ");
}
}
}
else if (byColumn && isRagged()) //
System.out.println("Cannot sort ragged arrays by column.");
}
【问题讨论】:
-
还有什么不完全有效?我还没有检查它,但你正在尝试做的应该与你的代码一起工作,只要它没有错误......
-
这两件事都是由相同的打印出来的:123 456 789
-
我相信它们都是成行打印的。
标签: java loops multidimensional-array