Sorting a 2D-Array Without Row or Column Order in JAVA

Ayush Gupta
3 min readSep 28, 2021

--

Hey, I is Ayush. Today, We Embark on a mission to Sort Out A 2D-Array. Well Yeah, As Every Other Programmer I tried Googling and tried to look it up on Stack-Overflow and all I received was just “unexplained-code” and “barely-making-sense” Algorithms. So, I took it up as a challenge (jk I needed it to solve a problem in school assignment) and began playing around with pen and paper.

Here, Is the Algorithm I Came Up With. 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.

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.

Twitter: @is_it_ayush

Stackoverflow: @Ayush

--

--