c++ sift down heap -


i writing program requires me use heap, , runs fine besides sorting methods, quite important! not sure wrong logic or if missing stupid. fresh set of eyes @ nice.

the function being passed vector of course heap, location of root, , either stl less or greater predicate.

template<class t,class p> void upheap(vector<t>& v, int start, p func) {    t x = v[start];    while (start > 1 && func(x, v[start/2])) {       v[start] = v[start/2]; start /= 2;    }    v[start] = x; }   

any idea wrong?

the first element in vector @ v[0]. seem assume it's @ v[1]. there reason this?

if root @ v[0], given node @ index i, parent @ int((i-1)/2) (though (i-1)>>1 might more efficient), , children @ 2i+1, 2i+2. e.g.:

     0    1   2  3  4 5  6 78 9a bc de 

on other hand, if root @ v[1], parent @ int(i/2) (or i>>1), , children @ 2i, 2i+1. e.g.:

     1    2   3  4  5 6  7 89 ab cd ef 

so issue.

you check see if func(x, v[start/2]) true. if func heap condition, may want check if that's false...

is vector large enough include v[start]? if upheap() being used add items heap 1 @ time... , vector's size never increased... (also, starting @ v[1], not v[0]. that's element.)

have tried writing simple scaffolding (code used testing/debugging not part of final product) routine print heap, adding loop, , running practice data see things go off kilter?


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -