Hello,
My current project uses a MAX Heap to keep a number of things organized. It's a simple Binary Heap (implemented as an array), mainly using:
-Insert(NODE n)
-Delete(NODE at index T)
-Update(NODE at index T with new value NVAL)
The number of Elements in constant and are saved in a vector of Elements. Only the Elements with a value above a certain threshold are in the Heap. This changes nothing for Insert and Delete, but results in the following cases for Update:
-Old Value < LIMIT:
--New Value < LIMIT: update value, stop.
--New Value > LIMIT: update value, Insert into Heap, stop.
-Old Value > LIMIT:
--New Value < LIMIT: Delete from Heap, update value, stop.
--New Value > Limit:
---New Value < Old Value: update value, Downsift, stop.
---New Value > Old Value: update value, Upsift, stop.
I used that flow table quite literally for the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
void HEAP::HUpdate(CNODE ij, VALUE nval) {
if (index(ij) == UNHEAPED) { // Same as val(ij) < LIMIT
val(ij) = nval;
if (nval > limit) HInsert(ij);
}
else {
if (nval < limit) {
HDelete(index(ij));
val(ij) = nval;
}
else {
if (nval > val(ij)) {
val(ij) = nval;
upsift(index(ij));
}
else {
val(ij) = nval;
downsift(index(ij));
}
}
}
}
|
It works, but I'm not satisfied with it. It looks inefficient. It might all be in my head, but when I see multiple nestings I become unhappy.
Is there a more efficient way of doing this? I can artificially reduce the nesting by replace the "else" with a "return" in the related "if" code, but I'm not sure if that's better.
Any and all tips are welcome in regards to nesting, even if they're not directly applicable to this specific problem!