Skip to content

Commit 4e06494

Browse files
add implementation for delete method for Heap
1 parent 2e7281f commit 4e06494

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

LearnProgrammingAcademy/src/Heap.java

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ public class Heap {
22
private int[] heap;
33
private int size;
44

5+
// constructs a max heap with initial capacity
56
public Heap(int capacity) {
67
this.heap = new int[capacity];
78
}
@@ -15,9 +16,30 @@ public void insert(int value) {
1516
size++;
1617
}
1718

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+
1839
private void heapifyAbove(int index) {
1940
int newValue = heap[index];
2041

42+
// shift parents down, assign value once
2143
while (index > 0 && newValue > heap[getParent(index)]) {
2244
heap[index] = heap[getParent(index)];
2345
index = getParent(index);
@@ -26,11 +48,55 @@ private void heapifyAbove(int index) {
2648
heap[index] = newValue;
2749
}
2850

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+
2986
private boolean isFull() {
3087
return size == heap.length;
3188
}
3289

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+
3398
private int getParent(int index) {
3499
return (index - 1) / 2;
35100
}
101+
36102
}

0 commit comments

Comments
 (0)