forked from Dev-XYS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Min-Heap.cpp
70 lines (58 loc) · 907 Bytes
/
Min-Heap.cpp
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
#include <cstdio>
#include <cstdlib>
#define MAX_HEAP_SIZE 100000
using namespace std;
int n, H[MAX_HEAP_SIZE], heapsize;
void min_heapify(int i)
{
int smallest = i;
int lch = i << 1;
int rch = lch + 1;
if (lch <= heapsize && H[smallest] > H[lch])
{
smallest = lch;
}
if (rch <= heapsize && H[smallest] > H[rch])
{
smallest = rch;
}
if (smallest != i)
{
int temp = H[smallest];
H[smallest] = H[i];
H[i] = temp;
min_heapify(smallest);
}
}
void build_heap()
{
for (int i = heapsize >> 1; i >= 1; i--)
{
min_heapify(i);
}
}
void insert(int x)
{
H[++heapsize] = x;
int ch = heapsize, p = heapsize >> 1;
while (H[p] > H[ch] && p >= 1)
{
int temp = H[p];
H[p] = H[ch];
H[ch] = temp;
ch = p;
p >>= 1;
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
int x;
scanf("%d", &x);
insert(x);
}
// Add more actions here.
return 0;
}