-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQ.java
More file actions
70 lines (60 loc) · 2.01 KB
/
PriorityQ.java
File metadata and controls
70 lines (60 loc) · 2.01 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
import java.io.IOException;
class MyPriorityQ {
//Элементы массива сортируются по значению ключа.
//от максимума (0) до минимума (size-1);
private int size, nItems;
private long[] arr;
//--------------------------------------------Конструктор
public MyPriorityQ(int size){
this.size = size;
arr = new long[size];
nItems = 0;
}
//-------------------------------------------Вставка
public void insert(long item){
int j;
if(nItems==0)
arr[nItems++]=item;
else{
for(j=nItems-1; j>=0; j--) {
if (item > arr[j])
arr[j + 1] = arr[j];
else
break;
}
arr[j+1]=item;
nItems++;
}
}
//------------------------------------------Извлечение минимального элемента
public long remove(){
return arr[--nItems];
}
//------------------------------------------Чтение минимального элемента
public long peekMin(){
return arr[nItems-1];
}
//------------------------------------------true, если очередь пуста
public boolean isEmpty(){
return nItems==0;
}
//------------------------------------------true, если очередь заполнена
public boolean isFull(){
return nItems==size;
}
}
/////////////////////////////////////////////////////////////////////////////
class PriorityQApp{
public static void main(String[] args) throws IOException{
MyPriorityQ pq = new MyPriorityQ(5);
pq.insert(30);
pq.insert(50);
pq.insert(10);
pq.insert(40);
pq.insert(20);
while(!pq.isEmpty()){
long item = pq.remove();
System.out.print(item+" ");
}
}
}