-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.java
More file actions
85 lines (57 loc) · 1.84 KB
/
PriorityQueue.java
File metadata and controls
85 lines (57 loc) · 1.84 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
//OUTLAB 1 by Zach Wadhams
public class PriorityQueue {
private int end;
private Job[] jobArray;
public Job IsNext() { //gets the next job
return jobArray[1];
}
public void Remove() { //removes the top job once it has been completed
jobArray[1] = jobArray[end - 1];
end --;
Sink(1);
}
public void Insert(Job job) { //inserts the job into the processor
jobArray[end] = job;
SwimUp(end);
end++;
}
private void SwimUp(int k) { //compares child with parent and either swaps them or does nothing
if (k == 1){ //basecase
return;
}
if (jobArray[k].priority > jobArray[k/2].priority) { //swap
Job myJob = jobArray[k];
jobArray[k] = jobArray[k/2];
jobArray[k/2] = myJob;
SwimUp(k/2);
}
}
private void Sink(int k) { //compares parent with child and either swaps them or does nothing
if (k*2 >= end) { //basecase
return;
}
int maxChildIdx = k * 2;
if (k * 2 + 1 < end) {
if (jobArray[k * 2].priority < jobArray[k * 2 + 1].priority) {
maxChildIdx = k * 2 + 1;
}
}
if (jobArray[maxChildIdx].priority > jobArray[k].priority) {
Job myJob = jobArray[k];
jobArray[k] = jobArray[maxChildIdx];
jobArray[maxChildIdx] = myJob;
Sink(maxChildIdx);
}
}
public PriorityQueue (int size) { //controls the size of the array
jobArray = new Job[size + 1];
this.end = 1;
}
public boolean IsEmpty () { //checks to see if the job is empty
boolean empty = false;
if (end == 1) {
empty = true;
}
return empty;
}
}