HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

An algorithm to efficiently insert a list of elements into a binary heap ("bulk insertion")

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
insertionefficientlyinsertelementsintobulkheapalgorithmbinarylist

Problem

I wonder if there is any elegant algorithm for inserting a list of elements into a binary heap (at once) whose performance would be close to that of inserting elements one by one when there are only a few elements to insert, and which would still run in linear time in the worst case (when there is a lot of elements to insert).

Solution

Wikipedia describes a procedure, due to Floyd, which constructs a heap from an array in linear time.

It also mentions a procedure for merging two heaps, of sizes $n$ and $k$, in time $O(k + \log k \log n)$.

Altogether, we can add $k$ elements to a heap of length $n$ in time $O(k + \log k \log n)$: first build a heap containing $k$ elements to be inserted (takes $O(k)$ time), then merge that with the heap of size $n$ (takes $O(k+ \log k \log n)$ time).

Compare this to repeated insertion, which would run in time $O(k\log n)$.

Context

StackExchange Computer Science Q#105086, answer score: 4

Revisions (0)

No revisions yet.