forked from biblelamp/JavaExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriorityQ.java
More file actions
70 lines (61 loc) · 2.07 KB
/
priorityQ.java
File metadata and controls
70 lines (61 loc) · 2.07 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
/**
* Book: Data Structures and Algorithms in Java, by Robert LaFore
* Chapter 4:
* priorityQ.java
* demonstrates priority queue
* to compile this code: javac priorityQ.java
* to run this program: java PriorityQApp
*/
class PriorityQ {
// array in sorted order, from max at 0 to min at size-1
private int maxSize;
private long[] queArray;
private int nItems;
public PriorityQ(int s) { // constructor
maxSize = s;
queArray = new long[maxSize];
nItems = 0;
}
public void insert(long item) { // insert item
int j;
if (nItems == 0) // if no items,
queArray[nItems++] = item; // insert at 0
else { // if items,
for (j=nItems-1; j>=0; j--) { // start at end,
if (item > queArray[j]) // if new item larger,
queArray[j+1] = queArray[j]; // shift upward
else // if smaller,
break; // done shifting
}
queArray[j+1] = item; // insert it
nItems++;
}
} // end insert()
public long remove() { // remove minimum item
return queArray[--nItems];
}
public long peekMin() { // peek at minimum item
return queArray[nItems-1];
}
public boolean isEmpty() { // true if queue is empty
return (nItems == 0);
}
public boolean isFull() { // true if queue is full
return (nItems == maxSize);
}
} // end class PriorityQ
class PriorityQApp {
public static void main(String[] args) {
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(30);
thePQ.insert(50);
thePQ.insert(10);
thePQ.insert(40);
thePQ.insert(20);
while(!thePQ.isEmpty()) {
long item = thePQ.remove();
System.out.print(item + " "); // 10, 20, 30, 40, 50
}
System.out.println("");
}
} // end class PriorityQApp