What is the time complexity of constructing a PriorityQueue from a collection?

后端 未结 1 1542
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 18:27

What is the complexity of Java\'s PriorityQueue constructor with a Collection? I used the constructor:

PriorityQueue(Collection

        
相关标签:
1条回答
  • 2020-12-17 19:15

    The time complexity to initialize a PriorityQueue from a collection, even an unsorted one, is O(n). Internally this uses a procedure called siftDown() to "heapify" an array in-place. (This is also called pushdown in the literature.)

    This is counterintuitive. It seems like inserting an element into a heap is O(log n) so inserting n elements results in O(n log n) complexity. This is true if you insert the elements one at a time. (Internally, inserting an individual element does this using siftUp().)

    Heapifying an individual element is certainly O(log n), but the "trick" of siftDown() is that as each element is processed, the number of elements that it has to be sifted past is continually decreasing. So the total complexity isn't n elements times log(n); it's the sum of n terms of the decreasing cost of sifting past the remaining elements.

    See this answer, and see also this article that works through the math.

    0 讨论(0)
提交回复
热议问题