-
Notifications
You must be signed in to change notification settings - Fork 0
/
pqueue.c
144 lines (125 loc) · 2.26 KB
/
pqueue.c
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/* pqueue.c
Implementation of an array-based heap for abstract
priority pqueue data type.
by: Jonathan Haywood
begun: March 19, 2006
*/
#include "bool.h"
#include "graph.h"
#include "pqueue.h"
init_queue(pqueue *q)
{
q->count = 0;
}
enqueue(pqueue *q, node * x)
{
int parent, leaf;
node value, temp;
if (q->count >= PQUEUESIZE)
{
printf("Warning: pqueue overflow enpqueue x=%dn",x);
return;
}
q->count++;
leaf = q->count - 1;
q->q[leaf] = *x;
// percolate up
parent = PARENT(leaf);
value = q->q[leaf];
while(leaf > 0 && (COST(q->q[leaf]) < COST(q->q[parent])))
{
temp = q->q[leaf];
q->q[leaf] = q->q[parent];
q->q[parent] = temp;
leaf = parent;
parent = PARENT(leaf);
}
q->q[leaf] = value;
}
node dequeue(pqueue *q)
{
int heapsize, root, childpos;
node minVal, temp;
node value;
minVal = q->q[0];
q->q[0] = q->q[q->count-1]; // take last element and put on root of tree
q->count--; // adjust size
root = 0;
if(q->count > 1)
{
// percolate down
heapsize = q->count;
value = q->q[root]; // get root
while(root < heapsize)
{
childpos = LEFT(root);
if(childpos < heapsize)
{
if((RIGHT(root) < heapsize) &&
(COST(q->q[childpos+1]) <
COST(q->q[childpos])))
{
childpos++;
}
if(COST(q->q[childpos]) < COST(q->q[root]))
{
temp = q->q[root];
q->q[root] = q->q[childpos];
q->q[childpos] = temp;
root = childpos;
}
else
{
q->q[root] = value;
break;
}
}
else
{
q->q[root] = value;
break;
}
}
}
return minVal;
}
int empty(pqueue *q)
{
if (q->count == 0) return (TRUE);
else return (FALSE);
}
int contains(pqueue *q, node *n)
{
int i;
for(i=0; i < q->count; i++)
{
if(q->q[i].data == n->data)
return (TRUE);
}
return (FALSE);
}
print_queue(pqueue *q)
{
int i;
printf("{ ");
for(i=0; i < q->count; i++) printf("%d ",q->q[i].data);
printf("}\n");
}
int main()
{
// Example use of priority queue
pqueue queue;
node n1, n2, n3;
n1.data = 1;
n1.cost = 1;
n2.data = 0;
n2.cost = 0;
n3.data = 3;
n3.cost = 3;
init_queue(&queue);
enqueue(&queue, &n1);
enqueue(&queue, &n2);
enqueue(&queue, &n3);
print_queue(&queue);
return 0;
}