Home > OS >  Sorting A Two-Dimensional (2D) Array as a whole without Row/Column Order
Sorting A Two-Dimensional (2D) Array as a whole without Row/Column Order

Time:09-30

I was working on a Two Dimensional Array and I need to sort it in as a whole and not as in One Row/One Column Sort. Say,

8   7   9   3
-2  0   4   5
1   3   6  -4

It should look like this,

-2  -1  0  1
 2   3  4  5
 6   7  8  9

CodePudding user response:

I did It. Took Two-Days to come up with an algorithm. Its not a perfect algorithm and maybe not even well optimized. But It Works.


Explanation

The Idea Is To get The Minimum Value From A Certain Element (say 0,0) To the End Of Array (i.e. a.length, a[0].length) and swapping it with the Certain Element. Here I have created a Diagram to better understand the logic.

N-Step Logic to Arrange Matrix As a Whole

We Do this Till We Reach The Last Element and Voila! We Have a Sorted 2D-Array.


Code [JAVA]

Now, Come's the fun Part from where I lost Two Brain Cells. The Code.

What I have done, Is To Create a function which returns me the minimum value In a Array. The Function takes two parameter's which is the Starting Element Index i.e.(i,j) from which its supposed to run a loop to end and return the minimum value with its index in a List.

//Helper Method

//row = Row Of Element To Began Loop From 
//column = Column Of Element To Began Loop From.
List get_min(int row,int column) 
{
    List<Integer> l = new ArrayList<Integer>();  // List To Return with the output.

    int mn=a[row][column], mni=0,mnj=0;    

    //mni= The Row Of Minimum Element
    // mnj = The Column Of Minimum Element

    for(int i=row;i<a.length;i  )
    {
        for(int j=column;j<a[0].length;j  )
        {
            if(mn>a[i][j])
            {
                mni = i;
                mnj = j;
                mn=a[i][j];
            }
        }
        column=0;  // This needs to be zero, just so the next time Row Updates The Loop doesn't began from the 2nd Element But 0.
    }
    l.add(mn); l.add(mni); l.add(mnj);
    return l;
}

Now We Have A List With Three Values, The Minimum Element, The Minimum Element Row, The Minimum Element Column. We Can Now Build A Simple, Swap Function with the Use of Helper Method Above.

void sort_array()
{
    for(int i=0; i<a.length;i  )
    {
        for(int j=0;j<a[0].length;j  )
        {
            List<Integer> l = get_min(i, j);  // List with Minimum Value As In Step 1,Step 2, Step 3
            if(a[i][j]>l.get(0))  // Check To Prevent Last Value Replacing The First Element
            {
                //Simple Swap
                int t = a[i][j];
                a[i][j] = l.get(0);
                a[l.get(1)][l.get(2)] = t;
            }
        }
    }
} 

Voila Now You Have An Sorted 2D-Array. Enjoy with the data.

  • Related