Home > Software design >  Custom Sorting in Priority Queue
Custom Sorting in Priority Queue

Time:10-19

My custom sort for PriorityQueue does not print in the way I wanted. I insert words with their frequencies in priorityQueue and when I poll them I should get the word with highest frequency and if frequencies of both words are same, I should get word which is smallest in lexicographical order. Somehow my custom priorityQueue does not work in that way.

import java.util.*;

class Pair {
    String word;
    int freq;

    Pair(String word, int frequency) {
        this.word = word;
        this.freq = freq;
    }
}

class SortCustom implements Comparator<Pair> {
    public int compare(Pair a, Pair b) {
        if(a.freq == b.freq)
            return a.word.compareTo(b.word);
        return b.freq - a.freq;
    }
}

public class HelloWorld {
    public static void main(String[] args) {
        PriorityQueue<Pair> queue = new PriorityQueue<>(new SortCustom());
        queue.add(new Pair("leaf",1));
        queue.add(new Pair("i",2));
        queue.add(new Pair("love",2));
        queue.add(new Pair("code",1));
        while(!queue.isEmpty()){
            System.out.println(queue.poll().word);
        }
    }
}

Output I get:

code
i
leaf
love

Output I want:

i
love
code
leaf

CodePudding user response:

It took me a while, but this doesn't have anything to do with PriorityQueue. The issue is the constructor of Pair:

    Pair(String word,int frequency){
        this.word=word;
        this.freq=freq;
    }

This should be

    Pair(String word,int freq) {
        this.word=word;
        this.freq=freq;
    }

You were always setting freq to its original value of 0, not to the argument passed to the constructor.

  • Related