【发布时间】:2015-05-01 18:09:25
【问题描述】:
作为作业的一部分,我应该编写一个方法,该方法使用插入排序根据每个 3D 数组中的双精度数对 4D 数组中的 3D 数组进行排序。
到目前为止我有这个方法,但它似乎只有在最小的 3D 数组 not 在最后一个位置时才有效(four[2],其中four 是一个 4D 数组有 3 个元素)。
public static void sort4DArray(double[][][][] list) {
int x;
for (int i = 1; i < list.length; i++) {
double[][][] currentElement = list[i];
//shifts the 3D arrays
for (x = i - 1; x >= 0 && count(list,x) > count(list,i); x--) {
list[x + 1] = list[x];
}
//inserts the 3D array to its new position
list[x + 1] = currentElement;
}
}
请注意,在此方法中,我使用另一种方法“count”来计算给定 3D 数组中有多少双精度数。我将下面的代码留作参考:
public static int count(double[][][][] list, int x) {
int count = 0;
for (int j=0; j < list[x].length; j++) {
for (int k=0; k < list[x][j].length; k++){
count += list[x][j][k].length;
}
}
return count;
}
这是两个示例输出,第一个是正确的,第二个是不正确的: 数组以括号的形式打印出来,希望通俗易懂。
数组中的数组是随机长度的(参差不齐),其中的双精度也是随机生成的。
{
{
{{0.5, 3.6, 8.9, }}
{{26.7, 20.5, 4.7, }}
{{15.3, }}
},
{
{{25.5, }}
},
{
{{15.8, 5.8, 0.2, }{12.7, }}
{{25.8, }}
},
}
After Sort:
{
{
{{25.5, }}
},
{
{{0.2, 5.8, 15.8, }{12.7, }}
{{25.8, }}
},
{
{{0.5, 3.6, 8.9, }}
{{4.7, 20.5, 26.7, }}
{{15.3, }}
},
}
这是第二个输出。请注意,最小的 3D 数组在第一次打印中是最后一个:
{
{
{{22.4, }{29.8, }{5.5, }}
{{10.2, 6.4, }}
},
{
{{13.4, }{24.0, }{3.5, 6.0, }}
{{14.1, 8.5, }{5.6, 14.3, }{22.1, }}
},
{
{{20.1, }}
},
}
After Sort:
{
{
{{22.4, }{29.8, }{5.5, }}
{{6.4, 10.2, }}
},
{
{{20.1, }}
},
{
{{13.4, }{24.0, }{3.5, 6.0, }}
{{8.5, 14.1, }{5.6, 14.3, }{22.1, }}
},
}
【问题讨论】:
标签: java arrays sorting multidimensional-array