-1

My question is similar to this one except instead of sorting by the first column, I'd like to be able to sort via the 2nd column.

double[][] myArr = new double[mySize][2];

The contents of the array would be:

1      5
13     1.55
12     100.6
12.1   .85

And what it should be after is:

12.1   .85
13     1.55
1      5
12     100.6

How would one go about doing that?

  • 1
    Have you looked at the answers to the linked question? Choose one or more of those to study. Figure out (it shouldn't be hard) where and how they choose the first elements of the member arrays to use for sorting. Modify that to choose the second element instead. – John Bollinger Apr 12 '23 at 18:35
  • Ayt I'mma be real with you, i am way too sleep deprived that while i was messing with the answers from the linked thread, i didn't realize that i already had the code correct and brushed it off. Sorry for wasting time but thank you so much for answering and making me realize. Have a good day m8 – CourierDude Apr 12 '23 at 18:48

1 Answers1

0

Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.

double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };

java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
    public int compare(double[] a, double[] b) {
        return Double.compare(a[1], b[1]); // only diff with linked answer
    }
});
John Williams
  • 4,252
  • 2
  • 9
  • 18