This repository has been archived by the owner on Aug 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
PriorityQueue.h
91 lines (73 loc) · 1.58 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
#ifndef PriorityQueue_h
#define PriorityQueue_h
#include <stdio.h>
#include <vector>
#include <iostream>
#include "Memory.h"
using namespace std;
class PriorityQueue
{
public:
unsigned long size()
{
return queue.size();
}
bool empty()
{
return size() == 0;
}
void push(PCB* key)
{
queue.push_back(key);
int index = size() - 1;
heapify_up(index);
}
void pop()
{
queue[0] = queue.back();
queue.pop_back();
heapify_down(0);
}
int front()
{
return queue[0]->id;
}
private:
vector<PCB*> queue;
int parent(int i)
{
return (i - 1) / 2;
}
int left_child(int i)
{
return (2 * i + 1);
}
int right_child(int i)
{
return (2 * i + 2);
}
void heapify_down(int i)
{
int left = left_child(i);
int right = right_child(i);
int smallest = i;
if (left < size() && queue[left]->priority < queue[i]->priority)
smallest = left;
if (right < size() && queue[right]->priority < queue[smallest]->priority)
smallest = right;
if (smallest != i)
{
swap(queue[i], queue[smallest]);
heapify_down(smallest);
}
}
void heapify_up(int i)
{
if (i && queue[parent(i)]->priority > queue[i]->priority)
{
swap(queue[i], queue[parent(i)]);
heapify_up(parent(i));
}
}
};
#endif /* PriorityQueue_hpp */