Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting a 2D Integer array based on a column
    text
    copied!<p>I have a 2D-array that I want to sort based on the second column. The first column should remain paired with the second column.</p> <p>The 2D-array is initially as follows (2x10 matrix):</p> <pre><code>0 10 1 9 2 9 3 9 4 15 5 10 6 4 7 8 8 11 9 12 </code></pre> <p>I want the above 2D-array to be sorted like this:</p> <pre><code>4 15 9 12 8 11 0 10 5 10 1 9 2 9 3 9 7 8 6 4 </code></pre> <p>Now, I've tried adapting the answer from: <a href="https://stackoverflow.com/questions/4907683/sort-a-two-dimensional-array-based-on-one-column">Sort a two dimensional array based on one column</a> into this code:</p> <pre><code>Arrays.sort(theArray, new Comparator&lt;Integer[]&gt;() { @Override public int compare(Integer[] int1, Integer[] int2) { Integer numOfKeys1 = int1[1]; Integer numOfKeys2 = int2[1]; return numOfKeys1.compareTo(numOfKeys2); } }); </code></pre> <p>However, it doesn't seem to sort the array at all. When printing the array after calling the sort() function the array is in its initial order.</p> <p>I also tried adapting the answer from here: <a href="https://stackoverflow.com/questions/5064027/sorting-2d-array-of-string-in-java">sorting 2D array of String in java</a> but I encountered the same problem.</p> <p>Have I made some fatal mistake when adapting these solutions, or should my code work?</p> <p>Also, how would I go about sorting this array in descending order? Would I replace the return statement in compare() with this line?</p> <pre><code>return -numOfKeys2.compareTo(numOfKeys1); </code></pre> <p>Any help would be greatly appreciated. Thanks!</p> <p>EDIT: Just posting the rest of my code to see if the problem is elsewhere.</p> <pre><code>public void Sort() { Integer[][] theArray = {{0,10},{1,9},{2,9},{3,9},{4,15},{5,10},{6,4},{7,8},{8,11},{9,12}};; dump(theArray); Arrays.sort(theArray, new Comparator&lt;Integer[]&gt;() { @Override public int compare(Integer[] int1, Integer[] int2) { Integer numOfKeys1 = int1[1]; Integer numOfKeys2 = int2[1]; return numOfKeys1.compareTo(numOfKeys2); } }); System.out.println("===="); dump(theArray); } public void dump(Integer[][] array) { for(int p = 0, q = 10; p &lt; q; p++) { System.out.println(array[p][0] + " " + array[p][1]); } } </code></pre> <p>EDIT 2:</p> <p>I've got it working. Thanks everyone for your help. I had multiple Sort() functions (an older one that wasn't working, and the one you see above), and it turns out I was calling the wrong one, even though I thought I changed the call. Just one of those days.</p> <p>Feel free to use the code above if you want to sort an array. It's fully working now.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload