-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryHeap.java
89 lines (67 loc) · 2.08 KB
/
BinaryHeap.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
package org.gra4j.trochilus;
import java.util.Arrays;
public class BinaryHeap <E extends Comparable<? super E>> {
private static final int DEFAULT_CAPACITY = 10;
private int currentSize;
private E[] array;
public BinaryHeap () {
this(DEFAULT_CAPACITY);
}
public BinaryHeap (int capacity) {
array = (E[]) new Comparable[capacity];
}
public BinaryHeap (E[] items) {
currentSize = items.length;
array = (E[]) new Comparable[(currentSize + 2) * 11 / 10];
int i = 1;
for (E element : items)
array[i++] = element;
buildHeap();
}
private void buildHeap() {
for (int i = currentSize/2; i > 0; i--)
percolateDown(i);
}
public E finMin () {
return array == null ? null : array[1];
}
public void insert (E element) {
if (currentSize == array.length-1)
enlargeArray(array.length*2 + 1);
int hole = ++currentSize;
for (array[0] = element; element.compareTo(array[hole/2]) < 0; hole /= 2)
array[hole] = array[hole/2];
array[hole] = element;
}
public E deleteMin () {
if (isEmpty())
throw new UnsupportedOperationException("heap is empty");
E element = finMin();
array[1] = array[currentSize--];
percolateDown(1);
array[currentSize + 1] = null;
return element;
}
private void percolateDown(int hole) {
int child;
E element = array[hole];
for (; hole * 2 <= currentSize; hole = child) {
child = hole * 2;
if (child != currentSize && array[child + 1].compareTo(array[child]) < 0)
child++;
if (element.compareTo(array[child]) > 0)
array[hole] = array[child];
else
break;
}
array[hole] = element;
}
public boolean isEmpty () {
return currentSize == 0;
}
public void enlargeArray (int newSize) {
array = Arrays.copyOf(array, newSize);
}
public void printHeap () {
}
}