Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building heap in O(N) in java instead of O(NlogN) [duplicate]

Tags:

java

heap

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)?

like image 933
Zephyr Avatar asked Oct 17 '25 08:10

Zephyr


1 Answers

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();
}
like image 140
that other guy Avatar answered Oct 19 '25 00:10

that other guy