简体   繁体   中英

SiftDown Algorithm Number of Comparisons

I was recently working with the siftDown algorithm used for building binary heaps. In the book "Algorithms and Data Structures: The Basic Toolbox" in exercise 6.5 it is stated that the given implementation of that algorithm needs 2*log(n) element comparisons. Now, I've tried to figure out why this is so, but I couldn't. Why is this correct?

When calling siftDown(i) you first perform two element comparisons:

  • The first is between h[2i] and h[2i+1] .
  • The second is between h[i] and h[m] .

After making the two comparisons you recursively call siftDown(m) where m=2i or m=2i+1 . That is, each call to siftDown() with an n -element heap results in making two element comparisons and a call to siftDown() with an n/2 -element heap.

Therefore, T(n) , the number of comparisons made when calling siftDown() with an n -element heap, satisfies:

T(n) = 2 + T(n/2)

The solution to this recurrence relation is

T(n) = 2logn

You can see that the above relation solves to 2logn by observing that each time, exactly 2 element comparisons are being made, and that the number of times is logn (because if you start with n and keep dividing by 2 over and over, you're done after logn divisions).

Hence, the total number of element comparisons made by siftDown() is about 2logn .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM