-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.java
More file actions
48 lines (39 loc) · 833 Bytes
/
PriorityQueue.java
File metadata and controls
48 lines (39 loc) · 833 Bytes
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
import java.util.Arrays;
public class PriorityQueue {
private int[] items = new int[5];
private int count;
// O(n)
public void add(int item) {
if (isFull())
throw new IllegalStateException();
var i = shiftItemsToInsert(item);
items[i] = item;
count++;
}
public boolean isFull() {
return count == items.length;
}
private int shiftItemsToInsert(int item) {
int i;
for (i = count - 1; i >= 0; i--) {
if (items[i] > item)
items[i + 1] = items[i];
else
break;
}
return i + 1;
}
// O(1)
public int remove() {
if (isEmpty())
throw new IllegalStateException();
return items[--count];
}
public boolean isEmpty() {
return count == 0;
}
@Override
public String toString() {
return Arrays.toString(items);
}
}