To build heap, we use PriorityQueue class in java. Is there a way using inbuilt library/class to build heap directly from an array in O(N) instead of pushing each element individually to build heap in O(NlogN)?
Use the constructor that takes a collection:
new PriorityQueue<String>(Arrays.asList(yourArray));
True to form, the Java Docs don't mention anything about complexity, but reading the source code shows that the OpenJDK uses the typical O(n)
heapify approach rather than inserting in a loop:
private void initFromCollection(Collection<? extends E> c) {
initElementsFromCollection(c);
heapify();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With