-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPriorityQueue.h
140 lines (119 loc) · 2.3 KB
/
PriorityQueue.h
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
#ifndef __PRIORITY_QUEUE_H__
#define __PRIORITY_QUEUE_H__
#define true 1
#define false 0
struct Heap
{
int numOfData;
int heapArr[];
};
struct PQueue
{
Heap heap;
};
// int compare function
int DataPriorityComp(int d1; int d2)
{
return d2 - d1;
}
void HeapInit(Heap heap)
{
heap.numOfData = 0;
heap.heapArr = array(-1);
}
int HIsEmpty(Heap heap)
{
if (heap.numOfData == 0)
{
return true;
}
return false;
}
int GetParentIDX(const int idx)
{
return idx / 2;
}
int GetLChildIDX(const int idx)
{
return idx * 2;
}
int GetRChildIDX(const int idx)
{
return GetLChildIDX(idx) + 1;
}
int GetHiPriChildIDX(Heap heap; const int idx)
{
if (GetLChildIDX(idx) > heap.numOfData)
{
return 0;
}
else if (GetLChildIDX(idx) == heap.numOfData)
{
return GetLChildIDX(idx);
}
else
{
if (DataPriorityComp(heap.heapArr[GetLChildIDX(idx)], heap.heapArr[GetRChildIDX(idx)]) < 0)
{
return GetRChildIDX(idx);
}
return GetLChildIDX(idx);
}
}
void HInsert(Heap heap; int data)
{
int idx = heap.numOfData + 1;
while (idx != 1)
{
if (DataPriorityComp(data, heap.heapArr[GetParentIDX(idx)]) > 0)
{
heap.heapArr[idx] = heap.heapArr[GetParentIDX(idx)];
idx = GetParentIDX(idx);
}
else
{
break;
}
}
heap.numOfData++;
resize(heap.heapArr, heap.numOfData + 1);
heap.heapArr[idx] = data;
}
int HDelete(Heap heap)
{
int retData = heap.heapArr[1];
int lastElem = heap.heapArr[heap.numOfData];
int parentIdx = 1;
int childIdx;
while (childIdx = GetHiPriChildIDX(heap, parentIdx))
{
if (DataPriorityComp(lastElem, heap.heapArr[childIdx]) >= 0)
{
break;
}
heap.heapArr[parentIdx] = heap.heapArr[childIdx];
parentIdx = childIdx;
}
heap.heapArr[parentIdx] = lastElem;
heap.numOfData--;
resize(heap.heapArr, heap.numOfData + 1);
return retData;
}
// PriorityQueue Wrapping
void PQueueInit(PQueue pq)
{
HeapInit(pq.heap);
}
int PQIsEmpty(PQueue pq)
{
return HIsEmpty(pq.heap);
}
void PEnqueue(PQueue pq; int data)
{
HInsert(pq.heap, data);
}
int PDequeue(PQueue pq)
{
return HDelete(pq.heap);
}
#endif