6

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

Alexey
  • 251
  • 1
  • 13

2 Answers2

5

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)$.

D.W.
  • 167,959
  • 22
  • 232
  • 500
Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514
4

A citation without too much consideration or research:
heap bulk insert, Elmasry/Katajainen style (figure 3):

procedure: bulk-insert
input: $A[1..n_0+l]$: array; $n_0$: index; $l$: index
data structures: $A[1..n_0]$: partial heap; $A[n_0+ 1..n_0+l]$: buffer
$right$$n_0+l$
$left$$\max \{n_0+ 1, \lfloor (n_0 + l)/2 \rfloor\}$
while $right \ne 1$
   $left ← \lfloor left/2 \rfloor$
   $right ← \lfloor right/2 \rfloor$
   for $j \in \{right, right−1, \cdots, left\}$
      sift-down$(A, j, n_0+l$)

Elmasry, Amr; Katajainen, Jyrki: Towards ultimate binary heaps

greybeard
  • 1,172
  • 2
  • 9
  • 24