@@ -2,6 +2,7 @@ public class Heap {
2
2
private int [] heap ;
3
3
private int size ;
4
4
5
+ // constructs a max heap with initial capacity
5
6
public Heap (int capacity ) {
6
7
this .heap = new int [capacity ];
7
8
}
@@ -15,9 +16,30 @@ public void insert(int value) {
15
16
size ++;
16
17
}
17
18
19
+ public int delete (int index ) {
20
+ if (isEmpty ()) {
21
+ throw new ArrayIndexOutOfBoundsException ("Heap is empty" );
22
+ }
23
+
24
+ int deletedValue = heap [index ];
25
+ int parent = getParent (index );
26
+
27
+ heap [index ] = heap [size - 1 ];
28
+
29
+ if (index == 0 || heap [index ] < heap [parent ]) {
30
+ heapifyBelow (index , size - 1 );
31
+ } else {
32
+ heapifyAbove (index );
33
+ }
34
+
35
+ size --;
36
+ return deletedValue ;
37
+ }
38
+
18
39
private void heapifyAbove (int index ) {
19
40
int newValue = heap [index ];
20
41
42
+ // shift parents down, assign value once
21
43
while (index > 0 && newValue > heap [getParent (index )]) {
22
44
heap [index ] = heap [getParent (index )];
23
45
index = getParent (index );
@@ -26,11 +48,55 @@ private void heapifyAbove(int index) {
26
48
heap [index ] = newValue ;
27
49
}
28
50
51
+ private void heapifyBelow (int index , int lastHeapIndex ) {
52
+ int childToSwap ;
53
+
54
+ while (index <= lastHeapIndex ) {
55
+ // get index of children
56
+ int leftChild = getChild (index , true );
57
+ int rightChild = getChild (index , false );
58
+
59
+ // child index is inside the heap, else break
60
+ if (leftChild <= lastHeapIndex ) {
61
+ // if this condition applies then there is no right child, we swap left child
62
+ // else we have to decide which is bigger of the two children
63
+ if (rightChild > lastHeapIndex ) {
64
+ childToSwap = leftChild ;
65
+ } else {
66
+ childToSwap = heap [leftChild ] > heap [rightChild ] ? leftChild : rightChild ;
67
+ }
68
+
69
+ // then swap or break out of loop in case no more swapping is necessary
70
+ if (heap [index ] < heap [childToSwap ]) {
71
+ int temp = heap [index ];
72
+ heap [index ] = heap [childToSwap ];
73
+ heap [childToSwap ] = temp ;
74
+ } else {
75
+ break ;
76
+ }
77
+
78
+ // update index for loop
79
+ index = childToSwap ;
80
+ } else {
81
+ break ;
82
+ }
83
+ }
84
+ }
85
+
29
86
private boolean isFull () {
30
87
return size == heap .length ;
31
88
}
32
89
90
+ private boolean isEmpty () {
91
+ return size == 0 ;
92
+ }
93
+
94
+ private int getChild (int index , boolean left ) {
95
+ return index * 2 + (left ? 1 : 2 );
96
+ }
97
+
33
98
private int getParent (int index ) {
34
99
return (index - 1 ) / 2 ;
35
100
}
101
+
36
102
}
0 commit comments