Double dimension array sorting in java

 

Double dimension array sorting in java

How to sort a two-dimensional array in Java

We can sort two-dimension arrays in Java easily. Here we have to convert the 2D array into a single dimension array. And do the sorting. In the following, we have applied the bubble sort technique.

A double dimension array is a row and col-wise array. It is used to store data in table formats. See the below picture

 

double dimension array

In the above-mentioned diagram we see a 2D array. 

public class DDA2SDA

{

    public static void main(String args[])

    {

        int n[][]={{10, 20, 30, 15}, {40, 50, 60, 47}, {70, 80, 90, 56}, {85, 49, 31, 22}};

        int num[] = new int[16];

        int i, j, k=0, t;

        System.out.println("DD Array elements");

        for(i=0;  i<4;  i++)

        {

            for(j=0; j<4; j++)

            {

                System.out.print(n[i][j] + "   ");               

            }

            System.out.println();

        }

        // Conversion of 2D array to single dimension array

        for(i=0; i<4; i++)

        {

            for(j=0; j<4; j++)

            {

               num[k] = n[i][j];

               k++;

            }         

        }

        // Applying Bubble Sorting on the SDA

        for(i=0; i<15; i++)

        {

            for(j=0; j<15-i; j++)

            {

                if(num[j] > num[j+1])

                {

                    t = num[j];

                    num[j] = num[j+1];

                    num[j+1] = t;

                }

            }

        }

        // Convert single dimension array  to double dimension array

        k = 0;

        for(i=0; i<4; i++)

        {

            for(j=0; j<4; j++)

            {

                n[i][j] = num[k];               

                k++;

            }           

        }

        // printing of Sorted data of DDA

        System.out.println("Sort DD Array elements");

        for(i=0; i<4; i++)

        {

            for(j=0; j<4; j++)

            {

                System.out.print(n[i][j] + "   ");               

            }

            System.out.println();

        }

    }

} // end of the class

output

double dimension array sorting



SHARE THIS
Previous Post
Next Post