Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- However with custom modification of Binary Heap you can get by with a single array of references, resulting into 4B per object, which is 16 times less than with the tree sets, and time per operation is still guaranteed O(log(n)).
- The modification is rather simple: with two comparators (call them C1 and C2):
- Each element on an odd floor (floor = height from the top) has to be lower or equal to all elements below it according to comparator C1
- Similarly, each element on an even floor has to be lower or equal to all elements below it according to comparator C2
- Now let's say that the root is at floor 1. Let's start with peek1() (read the minimum element according to C1) that is simply the root. For peek2(), we need to check the root and it's direct 2 children, but among these 3, the minimum according to C2 must be.
- The add() operation will be a bit more difficult, make sure you understand the add in regular heap first.
- Add the new element at the first unused position as usual.
- Check if it is greater or equal to the element 2 floors above according to that element's comparator. If it is, do nothing. If not, swap these 2 elements.
- Check if the element at the inserting position if greater or equal to it's parent according to parent's floor's comparator. If it is, do nothing. If not, swap these 2 elements.
- If swapping was made in point 2, repeat from point 1 as if the swapped element was newly inserted. Else if swapping was made in point 3, do the same. Else work is done.
- Similar to removing, just remove the lowest element, replace it with the last element and bubble it down. When testing the 2-floor relation, you must go through all 4 grand children, but the idea is the same.
- Also heap can be stored in an array so it saves a lot of memory in comparation to trees. If would like more detail on how and why the add() and pop() methods work, just write in the comments and i'll add explanation with pictures and everything.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement