-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathHeap.java
98 lines (83 loc) · 2.85 KB
/
Heap.java
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
package ch_23.exercise23_05;
import java.util.Comparator;
public class Heap<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<>();
/**
* Exercise23_05
*/
private final Comparator<? super E> comparator;
/**
* Create a default heap
* Exercise23_05
*/
public Heap(Comparator<? super E> comparator) {
this.comparator = comparator;
}
/**
* Create a heap from an array of objects
* Exercise23_05
*/
public Heap(E[] objects, Comparator<? super E> comparator) {
this.comparator = comparator;
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
/**
* Add a new object into the heap
*/
public void add(E newObject) {
list.add(newObject); // Append to the heap
int currentIndex = list.size() - 1; // The index of the last node
while (currentIndex > 0) {
int parentIndex = (currentIndex - 1) / 2;
// Swap if the current object is greater than its parent
// Exercise23_05
if (comparator.compare(list.get(currentIndex), list.get(parentIndex)) > 0) {
E temp = list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
} else
break; // The tree is a heap now
currentIndex = parentIndex;
}
}
/**
* Remove the root from the heap
*/
public E remove() {
if (list.size() == 0) return null;
E removedObject = list.get(0);
list.set(0, list.get(list.size() - 1));
list.remove(list.size() - 1);
int currentIndex = 0;
while (currentIndex < list.size()) {
int leftChildIndex = 2 * currentIndex + 1;
int rightChildIndex = 2 * currentIndex + 2;
// Find the maximum between two children
if (leftChildIndex >= list.size()) break; // The tree is a heap
int maxIndex = leftChildIndex;
if (rightChildIndex < list.size()) {
// Exercise 23 05
if (comparator.compare(list.get(maxIndex), list.get(rightChildIndex)) < 0) {
maxIndex = rightChildIndex;
}
}
// Swap if the current node is less than the maximum
// Exercise23_05
if (comparator.compare(list.get(currentIndex), list.get(maxIndex)) < 0) {
E temp = list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, temp);
currentIndex = maxIndex;
} else
break; // The tree is a heap
}
return removedObject;
}
/**
* Get the number of nodes in the tree
*/
public int getSize() {
return list.size();
}
}