Chad Brown
Chad Brown

Reputation: 1

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. 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. 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;
    }

Upvotes: 0

Views: 2609

Answers (1)

Don Roby
Don Roby

Reputation: 41135

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. The internal arrays (i.e., 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.

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--;
            }
        }
    }

}

Upvotes: 2

Related Questions