[Data Structure] Priority Queue

Priority Queue

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
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Priority_Queue{
private:
int *DATA;
int capacity;
int size;
void SWAP(int* A, int* B){
int temp = *A;
*A = *B;
*B = temp;
}
public:
Priority_Queue(int c) : capacity(c) {
DATA = (int*)malloc(sizeof(int)*capacity);
size = 1;
};
Priority_Queue() {
capacity = 10;
DATA = (int*)malloc(sizeof(int)*capacity);
size = 1;
};
void push(int n){
printf("PUSH %d\n",n);
if(size==capacity){
capacity*=2;
int *temp = (int*)malloc(sizeof(int)*capacity);
for(int i = 1; i < size; i++)
temp[i] = DATA[i];
free(DATA);
DATA = temp;
}
DATA[size++] = n;
int cur = size-1;
while(DATA[cur]>DATA[cur/2]&&(cur/2)!=0){
SWAP(&DATA[cur],&DATA[cur/2]);
cur /= 2;
}
}
int pop(){
if(size==1){
printf("IS EMPTY\n");
return -1;
}
int ret = DATA[1];
DATA[1] = DATA[--size];
int cur = 1, left = 2, right = 3;
while(cur<size){
int next = cur;
if(left<size&&DATA[cur]<DATA[left]) next = left;
if(right<size&&DATA[cur]<DATA[right]&&DATA[right]>DATA[left]) next = right;
if(next==cur) break;
SWAP(&DATA[cur],&DATA[next]);
cur = next;
left = cur*2;
right = left+1;
}
return ret;
}
};
int main(int argc, char** argv){
Priority_Queue pq;
for(int i = 1; i<=10;i++)
pq.push(i);
for(int i = 1; i <= 10; i++)
printf("POP : %d\n",pq.pop());
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/21/DataStructure/priority-queue/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.