-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.java
More file actions
151 lines (101 loc) · 2.71 KB
/
Copy pathPriorityQueue.java
File metadata and controls
151 lines (101 loc) · 2.71 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package SortingAlgorithm;
import java.lang.reflect.Array;
public class PriorityQueue<T extends Comparable<T>> {
private Heap<T> pq;
public PriorityQueue(Class<T> _clazz) {
pq = new Heap<>(_clazz);
}
public void pop() {
pq.pop();
}
public void push(T data) {
pq.add(data);
}
public T top() {
return pq.top();
}
}
class Heap<T extends Comparable<T>> {
private T[] heap;
private int capacity;
private int pos;
private Class<T> clazz;
public Heap(Class<T> _clazz) {
clazz = _clazz;
capacity = 10;
pos = 0;
heap = (T[]) Array.newInstance(clazz, capacity);
}
private void swap(int idx1, int idx2) {
T tmp = heap[idx1];
heap[idx1] = heap[idx2];
heap[idx2] = tmp;
}
private boolean empty() {
return pos == 0;
}
private void doubleTree() {
T[] newHeap = (T[])Array.newInstance(clazz, capacity * 2);
for(int i = 0; i < capacity; ++i)
newHeap[i] = heap[i];
capacity = capacity * 2;
heap = newHeap;
}
public void pop() {
getMin();
}
public T top() {
return (empty()) ? null : heap[1];
}
public void add(T data) {
if(pos == capacity - 1)
doubleTree();
heap[++pos] = data;
int tPos = pos;
int parPos = tPos/2;
while(0 < tPos && 0 < parPos) {
if(heap[tPos].compareTo(heap[parPos]) < 0)
swap(tPos, parPos);
else
break;
tPos = parPos;
parPos = tPos/2;
}
}
public T getMin() {
if(empty()) return null;
T returnVal = heap[1];
swap(1, pos);
pos--;
int tPos = 1;
while(tPos <= pos) {
int left = tPos * 2;
int right = tPos * 2 + 1;
if(right <= pos) {
int smaller = (heap[left].compareTo(heap[right]) < 0) ? left : right;
if(heap[tPos].compareTo(heap[smaller]) > 0) {
swap(tPos, smaller);
tPos = smaller;
} else {
break;
}
} else if(left <= pos) {
if(heap[tPos].compareTo(heap[left]) > 0) {
swap(tPos, left);
tPos = left;
} else {
break;
}
} else {
break;
}
}
return returnVal;
}
public void printTree() {
if(empty()) return;
// level 순회
for(int i = 1; i <= pos; ++i)
System.out.println(heap[i]);
}
}