Home > Software design >  sorting array of arrays in descending order using arrays.sort function is resulting in errors in jav
sorting array of arrays in descending order using arrays.sort function is resulting in errors in jav

Time:02-02

problem:https://leetcode.com/problems/maximum-units-on-a-truck/ I am supposed to sort array of arrays of size 2(eg. [[1,3],[2,2],[3,1]]) in descending order according to 2nd value of the inner element. i.e for 1st element[1,3]according to value 3. , but my code is resulting in error: no suitable method found for sort().Some Help would be appreciated.

here is my code in java

class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        Arrays.sort(boxTypes, new Comparator<int[][]>() {
                    public int compare(final int[][] entry1, final int[][] entry2) {
                        if (entry1[0][0] < entry2[0][0])
                            return 1;
                        else return -1;
                    }
                }
        );
        for (int i = 0; i < boxTypes.length; i  )
            System.out.println(boxTypes[i]);
        return 0;
    }
}

CodePudding user response:

As mentioned in comments, you are sorting by inner element, which is int[], so you need Comparator<int[]>.

public class Solution {

    public static void main(String[] args) {
        int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
        Arrays.sort(input, new Comparator<int[]>() {

            @Override
            public int compare(int[] o1, int[] o2) {
                return Integer.compare(o2[1], o1[1]);
            }
        });
        System.out.println(Arrays.deepToString(input));
    }
}

Note return Integer.compare(o2[1], o1[1]);, second parameter is compared to first in order to achieve descending order.

You could also achieve same effect using lambda, to make it shorter and more readable.

public class Solution {

    public static void main(String[] args) {
        int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
        System.out.println("Initial array - "   Arrays.deepToString(input));
        Arrays.sort(input, (o1, o2) -> Integer.compare(o2[1], o1[1]));
        System.out.println("Sorted array - "   Arrays.deepToString(input));
    }
}

CodePudding user response:

First, you can't use native type in <>, you need to use Integer instead. Then what you need to compare is the inner array Integer[] if I'm not mistaken so your comparator can't work. Here you are just trying to sort 2 arrays of arrays based on the first element of the first array.

Here is what I would do (using stream):

Integer[][] sortedBoxTypes = Arrays.stream(boxTypes).sorted(Comparator.comparing(entry -> entry[1])).toArray(Integer[][]::new);
  •  Tags:  
  • Related