0

This is my unsorted array:

P  B    A 
1  135  0
2  102  100
3  56   100
4  148  0
5  125  200
6  65   200

This is what my current array has after I sorted it this is the output I get

P  B    A 
1  135  0  
4  148  0  
3  56  100  
2  102  100  
6  65  200  
5  125  200 

I want my array to sort B by the biggest number depending A like this example.

P  B    A 
4  148  0    
1  135  0  
2  102  100 
3  56  100  
5  125  200    
6  65  200

This is currently my code:

Arrays.sort(x, new Comparator<int[]>() {
    public int compare(int[] o1, int[] o2) {
        int ret = Integer.compare(o1[2], o2[2]);
        // if the entries are equal at index 2, compare index 1
        if (0 == ret) {
            ret = Integer.compare(o1[1], o2[1]);
        }
        return (ret);
    }
});

2 Answers 2

1

Just invert the comparison of B in the comparator:

if (ret == 0) {
    ret = Integer.compare(o2[1] , o1[1]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

but the A values are not from Longest to small when is A a 100 for example
you have to insert my code into your comparator-class. just replace the if-block with the one from my answer
0

As far as I can see, the second sorting criterion (the one for the first field) comes in the reverse order, so revert the comparison result (note the added - operator):

if (0 == ret) {
    ret = -Integer.compare(o1[1], o2[1]);
}

2 Comments

why so inefficient? just swap o1[1] with o2[1]. same result, no additional operations. i know, it's peanuts, but still
You're probably right, but in my opinion that thing is much easier to overlook than the - operator when reading the code. And, to be honest, there should be a distinct class for those data records that implements Comparable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.