1+ public class Heap <E extends Comparable <E >> {
2+ private java .util .ArrayList <E > list = new java .util .ArrayList <>();
3+
4+ /** Create a default heap */
5+ public Heap () {
6+ }
7+
8+ /** Create a heap from an array of objects */
9+ public Heap (E [] objects ) {
10+ for (int i = 0 ; i < objects .length ; i ++)
11+ add (objects [i ]);
12+ }
13+
14+ /** Add a new object into the heap */
15+ public void add (E newObject ) {
16+ list .add (newObject ); // Append to the heap
17+ int currentIndex = list .size () - 1 ; // The index of the last node
18+
19+ while (currentIndex > 0 ) {
20+ int parentIndex = (currentIndex - 1 ) / 2 ;
21+ // Swap if the current object is less than its parent
22+ if (list .get (currentIndex ). compareTo (
23+ list .get (parentIndex )) < 0 ) {
24+ E temp = list .get (currentIndex );
25+ list .set (currentIndex , list .get (parentIndex ));
26+ list .set (parentIndex , temp );
27+ }
28+ else
29+ break ; // The tree is a heap now
30+
31+ currentIndex = parentIndex ;
32+ }
33+ }
34+
35+ /** Remove the root from the heap */
36+ public E remove () {
37+ if (list .size () == 0 ) return null ;
38+
39+ E removedObject = list .get (0 );
40+ list .set (0 , list .get (list .size () - 1 ));
41+ list .remove (list .size () - 1 );
42+
43+ int currentIndex = 0 ;
44+ while (currentIndex < list .size ()) {
45+ int leftChildIndex = 2 * currentIndex + 1 ;
46+ int rightChildIndex = 2 * currentIndex + 2 ;
47+
48+ // Find the maximum between two children
49+ if (leftChildIndex >= list .size ()) break ; // The tree is a heap
50+ int maxIndex = leftChildIndex ;
51+ if (rightChildIndex < list .size ()) {
52+ if (list .get (maxIndex ).compareTo (
53+ list .get (rightChildIndex )) > 0 ) {
54+ maxIndex = rightChildIndex ;
55+ }
56+ }
57+
58+ // Swap if the current node is greater than the maximum
59+ if (list .get (currentIndex ).compareTo (
60+ list .get (maxIndex )) > 0 ) {
61+ E temp = list .get (maxIndex );
62+ list .set (maxIndex , list .get (currentIndex ));
63+ list .set (currentIndex , temp );
64+ currentIndex = maxIndex ;
65+ }
66+ else
67+ break ; // The tree is a heap
68+ }
69+
70+ return removedObject ;
71+ }
72+
73+ /** Get the number of nodes in the tree */
74+ public int getSize () {
75+ return list .size ();
76+ }
77+ }
0 commit comments