作为赋值的一部分,我应该编写一个方法,使用插入排序来根据每个3D数组中的双倍数对4D数组中的3D数组进行排序。
到目前为止,对于这个方法,我已经做到了这一点,但是似乎只有当最小的3D数组是而不是在最后一个位置时才能工作(four[2],four是一个包含3个元素的4D数组)。
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;
}
}请注意,在此方法中,我使用了另一种方法“计数”,它计算给定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, }}
},
}发布于 2015-05-01 18:12:49
首先,我将简化您的count()函数,使其减少一个维度:
public static int count(double[][][] list) {
int count = 0;
for (int j=0; j < list.length; j++) {
for (int k=0; k < list[j].length; k++){
count += list[j][k].length;
}
}
return count;
}在此之后,我们将您对count(list, x)的旧调用替换为对count(list[x])的新调用。
至于插入排序,修复很简单:将count(list[x]) > count(list[i])更改为count(list[x]) > count(currentElement)。这是因为在您定义的内部循环的第一次迭代时,list[i]会被list[x + 1] = list[x]逻辑覆盖。(注意:我已经用数百万随机测试用例验证了这个固定算法。)
https://stackoverflow.com/questions/29992482
复制相似问题