Ifrahim Hernandez
Ifrahim Hernandez

Reputation: 105

Sorting Array by biggest number

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);
    }
});

Upvotes: 0

Views: 65

Answers (2)

user4668606
user4668606

Reputation:

Just invert the comparison of B in the comparator:

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

Upvotes: 1

gvlasov
gvlasov

Reputation: 20015

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]);
}

Upvotes: 0

Related Questions