-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercise2.java
138 lines (90 loc) · 2.16 KB
/
Exercise2.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
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
package priority_queue_exercises;
/*
* Give the heap that results when the keys E A S Y Q U E S T I O N
* are inserted in that order into an initially empty max-oriented heap
*/
@SuppressWarnings("unchecked")
public class Exercise2<Key extends Comparable<Key>> {
private int N;
private Key[]pq;
private static final int INITIAL_SIZE = 10;
public Exercise2() {
pq = (Key[])new Comparable[INITIAL_SIZE];
}
private int size() {
return N;
}
private boolean isEmpty() {
return N == 0;
}
private void resize(int sz) {
Key[] temp = (Key[]) new Comparable[sz];
for(int i = 1; i <= N; i++) {
temp[i] = pq[i];
}
pq = temp;
}
private boolean less(int i, int j) {
return pq[i].compareTo(pq[j]) < 0;
}
private void exchange(int i, int j) {
Key v = pq[i];
pq[i] = pq[j];
pq[j] =v;
}
private void sink(int index) {
while(2 * index <= N) {
int j = 2*index;
if(j < N && less(j, j+1))
j++;
if(! less(index, j))
break;
exchange(index, j);
index = j;
}
}
private void swim(int index) {
while(index > 1 && less(index/2, index)) {
exchange(index/2, index);
index /=2;
}
}
private void put(Key v) {
if(N+1 == pq.length)
resize(1+ N *2);
pq[++N] = v;
swim(N);
}
private Key delMax() {
Key k = pq[1];
exchange(1, N--);
sink(1);
pq[N+1] =null;
if(4*N <= pq.length)
resize(1+ 2*N);
return k;
}
//method that displays the internal arrangements of the queue
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[ ");
while(! isEmpty()) {
if(size() > 1) {
builder.append(delMax()).append(", ");
}
else
builder.append(delMax());
}
return builder.append(" ]").toString();
}
public static void main(String[] args) {
String[] c = {"E","A","S","Y","Q","U","E","S","T","I","O","N"};
Exercise2<String> pq = new Exercise2();
for(String ch: c) {
pq.put(ch);
}
System.out.println(pq);
// the output shows the items in the priority queue was of the arrangement: [ Y, U, T, S, S, Q, O, N, I, E, E, A ]
}
}