Iterating through PriorityQueue doesn't yield ordered results

后端 未结 3 1123
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 00:56
import java.util.*;
class Priority{  
public static void main(String args[]){  

PriorityQueue queue=new PriorityQueue();  
queue.add(\"Amit\         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-25 01:46

    Most of the time a priority queue is implemented using a heap datastructure. A heap is a tree which guarantees that

    if A is parent of B , then A < B

    It doesnt guarantee any other ordering. It is sufficient to provide the minimum element in constant time, to add an element in log time and to remove the key in log time.

    It just happen that the iterator itr traverses the heap using a pre-order transversal.

    Traverse(node)
       visit(node)
       Traverse(node.left())
       Traverse(node.right())
    

    Which explains your result.

    note: In java < is provided by implementing Comparable

提交回复
热议问题