1 /*优先队列--是对队列的一种改进
2 *要存储的数据存在优先级--数值小的优先级高--在队头
3 *优先队列的实现
4 *1.数组:适合数据量小的情况(没有用rear+front实现)
5 *优先队列头在items-1,队列尾在0是固定的
6 *2.堆:适合数据量大的情况
7 *优先队列的效率:插入O(N)移除O(1)
8 *优先队列的应用:操作系统线程调度算法
9 * */
10 public class MyPriorityQueue {
11 private int maxSize;
12 private long[] arr;//插入的时候保证有序
13 private int items;
14
15 public MyPriorityQueue(int s) {
16 maxSize = s;
17 arr = new long[maxSize];
18 items = 0;
19 }
20
21 public void insert(long key){
22 int j;
23 if(items == 0){//为空直接加入
24 arr[items++] = key;
25 }
26 else{//不为空就将小元素方在最上面--队列头
27 for(j = items-1;j >= 0;j--){
28 if(key > arr[j]){
29 arr[j+1] = arr[j];
30 }
31 else{
32 break;
33 }
34 }
35 arr[j+1] = key;
36 items++;
37 }
38 }
39
40 public long remove(){
41 return arr[--items];
42 }
43
44 public boolean isEmpty(){
45 return items == 0;
46 }
47
48 public boolean isFull(){
49 return items == maxSize;
50 }
51
52 public long getPeekMin(){
53 return arr[items -1];
54 }
55
56 public void diaplayPQ(){
57 for(int i = items- 1;i >= 0;i--){
58 System.out.print(arr[i] + " ");
59 }
60 System.out.println();
61 }
62 }