1

I want to make a priority queue of nodes, wherein priority of nodes is their frequencies. But the output doesn't contain the first element in the right position, rest all are in correct positons.

    import java.util.*;
class node implements Comparable<node>{
        char key;
        int freq;
        node(){}
        node(char k,int f){
                key=k;
                freq=f;
        }
    public int compareTo(node n){
            if(freq>n.freq)return 1;
            return 0;
        }
}

public class test{
    public static void main(String[] args){
        node x=new node('x',4);
        node a=new node('a',2);
        node b=new node('b',1);
        node c=new node('c',7);
        PriorityQueue<node> q = new PriorityQueue<node>();

        q.offer(a);
        q.offer(b);
        q.offer(c);
        q.offer(x);

        while(!q.isEmpty()){
            node d=q.poll();
            System.out.println(d.key+" "+d.freq);
        }
    }
}   

Output:

    a 2
    b 1
    x 4
    c 7

Should not the ordering be b , a, x, c Thanks.

2 Answers 2

5

Your comparator is wrong: if freq < n.freq, it returns 0 instead of returning a negative number.

The code should be

return Ints.compare(freq, n.freq); // with Guava

or

return Integer.valueOf(freq).compareTo(Integer.valueOf(n.freq)) // with plain Java

or

if (freq > n.freq) return 1;
if (freq < n.freq) return -1;
return 0;
Sign up to request clarification or add additional context in comments.

2 Comments

then what is the need of returning o?
0 is returned when objects are considered equal, i.e. when the frequencies are the same.
2

Add
else if (freq<n.freq) return -1;
into public int compareTo(node n)

Comments

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.