-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIndexPQ.java
More file actions
86 lines (71 loc) · 2.4 KB
/
Copy pathIndexPQ.java
File metadata and controls
86 lines (71 loc) · 2.4 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
/*********************************************************************
* Indirect priority queue.
*
* The priority queue maintains its own copy of the priorities,
* unlike the one in Algorithms in Java.
*
* This code is from "Algorithms in Java, Third Edition,
* by Robert Sedgewick, Addison-Wesley, 2003.
*********************************************************************/
public class IndexPQ {
private int N; // number of elements on PQ
private int[] pq; // binary heap
private int[] qp; //
private double[] priority; // priority values
public IndexPQ(int NMAX) {
pq = new int[NMAX + 1];
qp = new int[NMAX + 1];
priority = new double[NMAX + 1];
N = 0;
}
public boolean isEmpty() { return N == 0; }
// insert element k with given priority
public void insert(int k, double value) {
N++;
qp[k] = N;
pq[N] = k;
priority[k] = value;
fixUp(pq, N);
}
// delete and return the minimum element
public int delMin() {
exch(pq[1], pq[N]);
fixDown(pq, 1, --N);
return pq[N+1];
}
// change the priority of element k to specified value
public void change(int k, double value) {
priority[k] = value;
fixUp(pq, qp[k]);
fixDown(pq, qp[k], N);
}
/**************************************************************
* General helper functions
**************************************************************/
private boolean greater(int i, int j) {
return priority[i] > priority[j];
}
private void exch(int i, int j) {
int t = qp[i]; qp[i] = qp[j]; qp[j] = t;
pq[qp[i]] = i; pq[qp[j]] = j;
}
/**************************************************************
* Heap helper functions
**************************************************************/
private void fixUp(int[] a, int k) {
while (k > 1 && greater(a[k/2], a[k])) {
exch(a[k], a[k/2]);
k = k/2;
}
}
private void fixDown(int[] a, int k, int N) {
int j;
while (2*k <= N) {
j = 2*k;
if (j < N && greater(a[j], a[j+1])) j++;
if (!greater(a[k], a[j])) break;
exch(a[k], a[j]);
k = j;
}
}
}