Search code examples
javapriority-queue

How to sort with PriorityQueue<int[]> 3-values in Java?


I am trying to sort with PriorityQueue and Comparator, but I don't know how to write method..

If third element is the same, I want to compare it to the first element. If the first element is also the same, i want to compare it to the second element.

I tried to write in compare method :

if(o1[2]<o2[2])
 return 1;
else if(o1[2]>o2[2])
 return -1;
return 0;

but not working.. plz hele me...

Queue<int[]> q = new PriorityQueue<int[]>(new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return 0;
    }
});

q.add(new int[] {2, 2, 2});
q.add(new int[] {2, 4, 2});
q.add(new int[] {3, 3, 2});
q.add(new int[] {3, 1, 2});
q.add(new int[] {2, 7, 1});
q.add(new int[] {4, 7, 1});

I want to get Queue datas

2 7 1

4 7 1

2 2 2

2 4 2

3 1 2

3 3 2


Solution

  • Do your comparison using different parts of the array. If you get a difference, return it, which allows sorting. If you don't get a difference, do another comparison using another array index. So in your case for third -> first -> second, use indexes 2, 0 and then 1.

        public int compare(int[] o1, int[] o2) {
            int out = compareUsingIndex (2, o1, o2);
            if (out !=0){
                return out;
            }
            out = compareUsingIndex (0, o1, o2);
            if (out !=0){
                return out;
            }
            return compareUsingIndex (1, o1, o2);
        }
        
        private int compareUsingIndex(int index, int[] o1, int[] o2){
            if (o1[index]==o2[index]){
               return 0;
             }
            else if (o1[index]>o2[index]){
               return 1;
             }
            return -1;
        }