Sorry if the terminology in the title was off. I'm trying to better understand the terms by using them more often.
Anyway, I'm currently working on a lab in a data structures class (using C++) where I have to build a Ternary Heap and compare it to a Binary Heap already given to us. Since I have some extra time I wanted to iron out some of the details in my code so that it is running as efficiently as possible.
My greatest concern is the amount of if-else statements that I'm using. I actually had to take ten minutes and organize the layout of them on paper just so I didn't get confused. (I'm not complaining, I just don't know if this is the best way to approach the problem or not.)
template<class T>
void TernaryHeap<T>::trickleDown(int i) {
do {
int j = -1;
int r = right(i);
if (r < n && compare(a[r], a[i]) < 0) {
int l = left(i);
if (compare(a[l], a[r]) < 0) {
j = l;
} else {
j = r;
}
int m = mid(i);
if (compare(a[m], a[r]) < 0) {
j = m;
} else {
j = r;
}
} else {
int l = left(i);
if (l < n && compare(a[l], a[i]) < 0) {
int m = mid(i);
if (compare(a[m], a[l]) < 0) {
j = m;
} else {
j = l;
}
}
}
if (j >= 0) a.swap(i, j);
i = j;
} while (i >= 0);
}
How would you go about finding the smallest element in a 2-element array? You'll probably find that a single if-else
is enough.
Now make the same thing for a 3-element array. Do you just add more conditionals? Or do you just write a generic algorithm that handles arrays of any size?
Your "sift-down" algorithm is done in two steps: find the smallest element, then swap it with the current element. You generalized the binary heap into a ternary heap by simply adding more tests, when you probably should have gone with the more general solution. What if you go to a 4-ary heap? Will you add even more if-else
tests?