Java 优先队列在内部是如何工作的呢?

huangapple go评论87阅读模式
英文:

How do Java Priority Queues Work Under The Hood?

问题

我似乎找不到任何信息来回答我的问题。因此,Java中的PriorityQueue是使用堆构建的。堆的插入和删除时间复杂度为O(logn),因此如果我要进行堆排序,时间复杂度将为O(nlogn)。

但是,在创建堆时只需要O(n)的时间。所以假设我加入以下代码行

PriorityQueue<Character> heap = new PriorityQueue<>(list);

Java是在使用值构建数据结构,因此时间复杂度是O(n),还是在之后插入,因此时间复杂度是O(nlogn)?

英文:

I cannot seem to find any information to answer my question. So Java PriorityQueue are built using heaps. Heaps have an insertion and deletion time of O(logn) so if I were to do a heap sort that would be O(nlogn).

But during creation of a heap it only takes O(n) time. So lets say I put the line

PriorityQueue&lt;Character&gt; heap = new PriorityQueue&lt;&gt;(list); 

Is Java building the data structure with the values so its O(n) or is it inserting afterwards so its O(nlogn)?

答案1

得分: 1

你可以随时查看源代码:http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/PriorityQueue.java

当你从未排序的列表初始化它时,它会使用O(n)的heapify方法。

英文:

You can always check the source: http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/PriorityQueue.java

When you initialize it from an unsorted list, it uses the O(n) heapify method.

huangapple
  • 本文由 发表于 2020年10月22日 13:28:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64475830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定