【问题标题】:Insertion Sort, 4 Dimensional Arrays Java插入排序,4 维数组 Java
【发布时间】: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


    【解决方案1】:

    首先,我会简化您的 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]) &gt; count(list[i]) 更改为count(list[x]) &gt; count(currentElement)。这是因为list[i] 在您定义的内部循环的第一次迭代中被list[x + 1] = list[x] 逻辑覆盖。 (注意:我已经用数百万个随机测试用例验证了这个固定算法。)

    【讨论】:

      猜你喜欢
      • 2018-10-06
      • 2021-05-27
      • 2021-03-01
      • 2023-03-06
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      相关资源
      最近更新 更多