简体   繁体   English

插入排序和2 d数组

[英]insertion sort and 2 d arrays

I'm trying to use insertion sort to sort a 2 d array in Java by the first column values of each row. 我正在尝试使用插入排序来按每行的第一列值对Java中的二维数组进行排序。 I've tested it on an array of size 2 but when I try the code for size 3 it doesn't even run the for loop. 我已经在大小为2的数组上进行了测试,但是当我尝试使用大小为3的代码时,它甚至都没有运行for循环。 Thank you for any help you can give. 感谢您提供任何帮助。

public int[][] sortC(int[][] temp)
    {
        if (temp.length == 1)       
        {
            return temp;
        }
        else if (temp.length >= 2)
        {
               for (int i = 1; i <= temp.length - 1; i++)
               {
                   int holdRow = temp[i][0];
                   int holdCol = temp[i][1];
                   // hold past index
                   int holdRowP = temp[i - 1][0];
                   int holdColP = temp[i - 1][1];

                   int j = i;

                   while (j > 0 && holdRow < holdRowP)
                   {
                       holdRow = temp[j][0];
                       holdCol = temp[j][1];
                       // hold past index
                       holdRowP = temp[j - 1][0];
                       holdColP = temp[j - 1][1];   

                       // make single swap
                       temp[j][0] = holdRowP;
                       temp[j][1] = holdColP;

                       temp[j-1][0] = holdRow;
                       temp[j-1][1] = holdCol;

                       j--;
                   }
               }
        }

        return temp;
    }

You can simplify alot and make it work for arbitrary size by using the fact that a Java 2D array is really an array of arrays. 通过使用Java 2D数组实际上是数组数组的事实,您可以简化很多并使其适用于任意大小。 The internal arrays (ie, the rows) can be moved around as whole units rather than piecemeal as you're doing. 内部数组(即行)可以作为整个单元移动,而不是像你一样零碎地移动。

As your code is modifying the passed argument, there's also no need to return the array. 由于您的代码正在修改传递的参数,因此也无需返回数组。

After the call sortC(input) , the input array will be sorted. 调用sortC(input)input数组将被排序。

Using both of these, your code can be reduced to 使用这两者,您的代码可以减少到

public void sortC(int[][] temp)
{
    if (temp.length >= 2)
    {
        for (int i = 1; i <= temp.length - 1; i++)
        {
            int[] hold = temp[i];
            int[] holdP = temp[i-1];

            int j = i;

            while (j > 0 && hold[0] < holdP[0])
            {
                hold = temp[j];
                holdP = temp[j-1];

                temp[j] = holdP;
                temp[j-1] = hold;

                j--;
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM