📜 ⬆️ ⬇️

Binary heap: proof of the complexity of the construction of O (n)

Actually, it will be a question of the binary heap and its construction using Sift-Down (or Heapify). Many probably know that building a heap in this way is done in image . Here I will give evidence of this fact.

Here is an example of the procedure for constructing a heap by array in the Pascal language.

procedure siftdown(v:longint); var min,l,r:longint; begin l:=v*2; r:=v*2+1; min:=v; if (l <= s) and (a[l] < a[min]) then min:=l; if (r <= s) and (a[r] < a[min]) then min:=r; if min <> v then begin swap(a[min], a[v]); sift_down(min); end; end; procedure build; var i:longint; begin for i:=n downto 1 do siftdown(i); end; 


So, let an array consisting of image elements, and image number of operator calls image (in the procedure image ) when building a heap on this array. Obviously image determines the time of the procedure image which is interesting to us.
')
Lemma.
Let for some element of the array when calling image was done image operator calls image . Then his index did not exceed image .

Evidence:

With image operator calls image index image element increases at least in image time. Now let image i.e. image . Then after image we have calls image that is impossible, as in our heap image items. image

Let us now estimate the magnitude above image . Let an array element have an index image . There is image such that image . Then in order for the array element with the index image He took his place in the heap will need no more image calls image (by the lemma). The number of elements with such indices is the value image that when image vanishes.

In this way,

image
With image the terms are zero (so the loop in the procedure image can start with image ).
We estimate the left multiplier in each term sum as

image

From here we have:

image

We estimate each of the amounts.

image

image

In this way, image .
image bounded above by a function that is image . So image .
Consequently, the time of the procedure image there is a proportional value image .

Source: https://habr.com/ru/post/195832/


All Articles