0

I read through the implementation of Java PriorityQueue, the constructors it has are:

PriorityQueue()

PriorityQueue(Collection<? extends E> c)

PriorityQueue(int initialCapacity)

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)

PriorityQueue(PriorityQueue<? extends E> c)

PriorityQueue(SortedSet<? extends E> c)

You can see there is no way to initialize a heap with a collection and custom comparator.

Definitely I can create a heap with custom comparator and call 'offer' iteratively to add elements but the time complexity will be O(n*logn).

On the other hand, if the heap can be initialized with a collection(with custom comparator) and call 'siftDown', the time complexity can be lowered to O(logn). How to achieve that using Java PriorityQueue?

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Weel
  • 132
  • 2
  • 7
  • 2
    I don't see how the complexity will be lower in case of collection and custom comparator as first all the collection objects need to be arranged based on comparator which would be O(n*logn) – Ankit Bansal Feb 28 '16 at 04:17
  • you are correct. looking at the code, there is no way to achieve what you want. should probably file a feature request with oracle. – jtahlborn Feb 28 '16 at 04:39
  • 1
    @AnkitBansal you can take a look to the wiki of how to build a heap https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap -- create a heap without doing any comparison and do a 'siftDown' will change the complexity to O(logN) – Weel Mar 01 '16 at 00:39
  • @jtahlborn sure i i will do that – Weel Mar 01 '16 at 00:40
  • 2
    See also: [Java Priority Queue Build Heap Process Time Complexity](https://stackoverflow.com/questions/66170496/java-priority-queue-build-heap-process-time-complexity) – Stuart Marks Apr 16 '22 at 00:32

0 Answers0