-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapImpl.java
More file actions
84 lines (73 loc) · 2.29 KB
/
HeapImpl.java
File metadata and controls
84 lines (73 loc) · 2.29 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
import java.util.Arrays;
class HeapImpl<T extends Comparable<? super T>> implements Heap<T> {
private static final int INITIAL_CAPACITY = 128;
private T[] _storage;
private int _numElements;
@SuppressWarnings("unchecked")
public HeapImpl () {
_storage = (T[]) new Comparable[INITIAL_CAPACITY];
_numElements = 0;
}
/**
* Adds to the heap
* @param data is what's added to the heap
*/
@SuppressWarnings("unchecked")
public void add (T data) {
if (_numElements + 1 > _storage.length) {
int newCapacity = _storage.length * 2;
T[] newStorage = (T[]) new Comparable[newCapacity];
for (int i = 0; i < _storage.length; i++) {
newStorage[i] = _storage[i];
}
_storage = newStorage;
}
_storage[_numElements] = data;
_numElements++;
int index = _numElements - 1;
while (index > 0) {
int parentIndex = (index - 1) / 2;
if (_storage[parentIndex].compareTo(_storage[index]) >= 0) {
break;
}
T temp = _storage[parentIndex];
_storage[parentIndex] = _storage[index];
_storage[index] = temp;
index = parentIndex;
}
}
/**
* Removes the first in the heap
*/
public T removeFirst () {
if (_numElements == 0) {
return null;
}
T firstElement = _storage[0];
_storage[0] = _storage[--_numElements];
_storage[_numElements] = null;
int index = 0;
while (true) {
int childIndex = index * 2 + 1;
if (childIndex >= _numElements) {
break;
}
if (childIndex + 1 < _numElements &&
_storage[childIndex].compareTo(_storage[childIndex + 1]) < 0) {
childIndex++;
}
if (_storage[childIndex].compareTo(_storage[index]) > 0) {
T temp = _storage[childIndex];
_storage[childIndex] = _storage[index];
_storage[index] = temp;
index = childIndex;
} else {
break;
}
}
return firstElement;
}
public int size () {
return _numElements;
}
}