-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHeap.java
More file actions
103 lines (85 loc) · 2.6 KB
/
Heap.java
File metadata and controls
103 lines (85 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package data_structures.heaps;
public class Heap {
private final int[] heap;
private int size;
public Heap(int capacity) {
heap = new int[capacity];
}
public void insert(int value) {
if (isFull()) {
throw new IndexOutOfBoundsException("Heap is full");
}
heap[size] = value;
fixHeapAbove(size++);
}
public int peek() {
if (isEmpty()) {
throw new IndexOutOfBoundsException("Heap is empty");
}
return heap[0];
}
public int delete(int index) {
if (isEmpty()) {
throw new IndexOutOfBoundsException("Heap is empty");
}
int parent = getParent(index);
int deletedValue = heap[index];
heap[index] = heap[size - 1];
if (heap[0] == 0 || heap[index] < heap[parent]) {
fixHeapBelow(index, size - 1);
} else fixHeapAbove(index);
size--;
return deletedValue;
}
private void fixHeapAbove(int index) {
int newValue = heap[index];
while (index > 0 && newValue > heap[getParent(index)]) {
heap[index] = heap[getParent(index)];
index = getParent(index);
}
heap[index] = newValue;
}
private void fixHeapBelow(int index, int lastHeapIndex) {
int childToSwap;
while (index <= lastHeapIndex) {
int leftChild = getChild(index, true);
int rightChild = getChild(index, false);
if (leftChild <= lastHeapIndex) {
if (rightChild > lastHeapIndex) {
childToSwap = leftChild;
} else {
childToSwap = (heap[leftChild] > heap[rightChild] ? leftChild : rightChild);
}
if (heap[index] < heap[childToSwap]) {
int tmp = heap[index];
heap[index] = heap[childToSwap];
heap[childToSwap] = tmp;
} else {
break;
}
index = childToSwap;
} else {
break;
}
}
}
public void printHeap() {
for (int i = 0; i < size; i++) {
System.out.print(heap[i]);
System.out.print(", ");
}
System.out.println();
}
public boolean isFull() {
return size == heap.length;
}
public int getParent(int index) {
return (index - 1) / 2;
}
public boolean isEmpty() {
return size == 0;
}
public int getChild(int index, boolean left) {
return 2 * index + (left ? 1 : 2);
}
}