Adding A Value To A Heap
It's Pretty Easy
You have studied the heap data structure and you know a couple of things now. The first element in the array is the top or root of the tree and the last valid element is the last node in the complete tree. The process for adding a value to a heap works as follows:
- The value is added at the "size" index of the array which always follows the last valid element
- The value is moved up the tree until the heap rules are met, meaning the value is less than its parent and greater than its children. This process is called bubbling up
That's it. The bubbling up process (for a min heap) in a nutshell is:
// check for current index greater than 0
// (top of tree, beginning of list)
// calculate parent's index
// check if current child's value is less than parent value
// swap the parent's and child's values
// call the function recursively with the parent's index
The code isn't too much more complicated than this.
Take a look at the video to see the whole process in action. As you can see in both the text and the video, the process is not very complicated.