Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
Priority Queue <Double> vs Priority Queue <Node>

Ok so I'm trying to use a java priority queue to sort nodes by the double val they contain. I know how to do a priority queue by double but I need the rest of the node values for a huffman encoding tree construction. Is there a way to sort a priority queue of nodes by their val or would I be better off making the queue sort the double vals and then trying to match them to the nodes?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You have two options, and the choice depends on what the Double means in the Node:

  1. Have Node implement Comparable<Node>, and use PriorityQueue<Node>. The compareTo method will order by the Double. The queue order you want is the natural order of the elements.
  2. Use the PriorityQueue constructor that takes a Comparator argument. The Comparator you use for the queue should order according to the Double value.

The first one is better if the Double really is the natural order for the nodes. The second one is better if it is only important for this queue, and other fields are equally important for other purposes.

over 4 years ago · Santiago Trujillo Report

0

You can use PriorityQueue<Node> implementation and manage the ordering of elements by overriding compare method of the Comparator interface during the queue construction time.

For example: To sort elements in ascending order of their Node values, use the below-mentioned declaration of the priority queue and then simply add nodes to the priority queue.

PriorityQueue<Node> pq = new PriorityQueue<Node>(new Comparator<Node>(){
   public int compare(Node node1, Node node2){
       if(node2.val>node1.val){
          return -1;
       }
       else{
          return 1;
       }
   }
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!