-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathBinaryHeap.java
More file actions
114 lines (94 loc) · 2.75 KB
/
Copy pathBinaryHeap.java
File metadata and controls
114 lines (94 loc) · 2.75 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
104
105
106
107
108
109
110
111
112
113
114
package ch06;
/**
* Created by cookfront on 2017/3/26.
*/
public class BinaryHeap<AnyType extends Comparable<? super AnyType>> {
private static final int DEFAULT_CAPACITY = 10;
private int currentSize;
private AnyType [ ] array;
public BinaryHeap() {
this(DEFAULT_CAPACITY);
}
public BinaryHeap(int capacity) {
currentSize = 0;
array = (AnyType[]) new Comparable[capacity + 1];
}
public BinaryHeap(AnyType [] items) {
currentSize = items.length;
array = (AnyType[]) new Comparable[(currentSize + 2) * 11 / 10];
int i = 1;
for (AnyType item : items) {
array[i++] = item;
}
buildHeap();
}
private void buildHeap() {
for (int i = currentSize / 2; i > 0; i--) {
percolateDown(i);
}
}
private void percolateDown(int hole) {
int child;
AnyType tmp = array[hole];
for (; hole * 2 <= currentSize; hole = child) {
child = hole * 2;
if (child != currentSize && array[child + 1].compareTo(array[child]) < 0) {
child++;
}
if (array[child].compareTo(array[hole]) < 0) {
array[hole] = array[child];
} else {
break;
}
}
array[hole] = tmp;
}
public void insert(AnyType x) {
if (currentSize == array.length - 1) {
enlargeArray(array.length * 2 + 1);
}
int hole = ++currentSize;
for (array[0] = x; x.compareTo(array[hole / 2]) < 0; hole /= 2) {
array[hole] = array[hole / 2];
}
array[hole] = x;
}
private void enlargeArray(int newSize) {
AnyType [] oldArr = array;
array = (AnyType []) new Comparable[newSize];
for (int i = 0; i < oldArr.length; i++) {
array[i] = oldArr[i];
}
}
public AnyType findMin() {
// if (isEmpty()) {
// throw new Exception();
// }
return array[1];
}
public boolean isEmpty() {
return currentSize == 0;
}
public AnyType deleteMin() {
// if (isEmpty()) {
// throw new Exception();
// }
AnyType minItem = array[1];
array[1] = array[currentSize--];
percolateDown(1);;
return minItem;
}
public void makeEmpty() {
currentSize = 0;
}
public static void main(String ...args) {
int numItems = 10000;
BinaryHeap<Integer> h = new BinaryHeap<>();
int i = 37;
for (i = 37; i != 0; i = (i + 37) % numItems)
h.insert(i);
for (i = 1; i < numItems; i++)
if (h.deleteMin() != i)
System.out.println("Oops! " + i);
}
}