-
Notifications
You must be signed in to change notification settings - Fork 0
/
PriorityQueue.java
42 lines (36 loc) · 935 Bytes
/
PriorityQueue.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
package com.brian.portfolio.datastructures;
public class PriorityQueue {
private int count;
private int[] items;
public PriorityQueue(int length) {
this.items = new int[length];
}
public void add(int item) {
if (isFull())
throw new IllegalStateException();
int i = shiftItemsToInsert(item);
items[i] = item;
count++;
}
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;
}
public int remove() {
if (isEmpty())
throw new IllegalStateException();
return items[--count];
}
public boolean isEmpty() {
return count == 0;
}
public boolean isFull() {
return count == items.length - 1;
}
}