Download presentation
Presentation is loading. Please wait.
1
Section 9.2b Adding and Removing from a Heap
2
The add method Concept: the heap is implemented as an ArrayList
Pseudocode: add(element): returns element add element to end of ArrayList // to maintain heap shape property call reheapUp(element) // to re-establish heap order property return element Note: reheapUp is outlined on the next two slides
4
reheapUp operation Concept:
element to be moved up is at end of ArrayList finds proper heap location for element Pseudocode: reheapUp(element) set an index variable (hole) to the end of the arraylist while(hole is not root and element > hole’s parent) move the hole’s parent element down (to hole) move the hole index up place element into final location (hole) Note that the formula for finding the index of the parent of any child is parentIndex = (childIndex – 1) / 2
5
The remove method Concept:
removes the object at the front (root) of the priority queue (heap) Pseudocode: remove: returns element: throws PQUnderflowException get (and store) the root element remove (and store) the last element in the ArrayList if(ArrayList is not empty) // make sure its not the last removal call reheapDown(last element) return root element Note: reheapDown is outlined on the next two slides
7
reheapDown operation Concept:
the current heap root position is “empty” move last item in ArrayList up move the empty hole down stop when the two locations meet Pseudocode: reheapDown(element) set hole index to zero // root location call newHole to find new hole location while(newHole not equal to hole) set the ArrayList element at hole location to element at new hole location set hole to new hole location set ArrayList element at hole location to element Note: newHole is outlined on the next slide
8
newHole method Concept:
Given a hole location, determine if the new hole location should be either in the left child, right child, or stay at the present location. Pseudocode: newHole(int hole, element): return index if either child of hole is larger than element return the index of the larger child else return the index of the current hole Note that the formula for the index of the left and right children is as follows int left = (hole * 2) + 1; // index for left child int right = (hole * 2) + 2; // index for right child
9
Heaps Versus Other Representations of Priority Queues
add remove
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.