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
|
#include "../common_heap_utility.h"
namespace CLRS
{
template <typename T, std::size_t n>
void max_heapify(T (&a)[n], std::size_t i, std::size_t length = n)
{
std::size_t l = CLRS::left(i);
std::size_t r = CLRS::right(i);
std::size_t largest = i;
if(l < length && a[l] > a[i])
largest = l;
if(r < length && a[r] > a[largest])
largest = r;
if(largest != i)
{
T temp = a[i];
a[i] = a[largest];
a[largest] = temp;
max_heapify(a, largest, length);
}
}
template <typename T>
void max_heapify(std::vector<T> &a, std::size_t i)
{
std::size_t l = CLRS::left(i);
std::size_t r = CLRS::right(i);
std::size_t largest = i;
if(l < a.size() && a[l] > a[i])
largest = l;
if(r < a.size() && a[r] > a[largest])
largest = r;
if(largest != i)
{
T temp = a[i];
a[i] = a[largest];
a[largest] = temp;
max_heapify(a, largest);
}
}
template <typename T, std::size_t n>
void min_heapify(T (&a)[n], std::size_t i, std::size_t length = n)
{
std::size_t l = CLRS::left(i);
std::size_t r = CLRS::right(i);
std::size_t minimum = i;
if(l < length && a[l] < a[i])
minimum = l;
if(r < length && a[r] < a[minimum])
minimum = r;
if(minimum != i)
{
T temp = a[i];
a[i] = a[minimum];
a[minimum] = temp;
min_heapify(a, minimum, length);
}
}
template <typename T>
void min_heapify(std::vector<T> &a, std::size_t i)
{
std::size_t l = CLRS::left(i);
std::size_t r = CLRS::right(i);
std::size_t minimum = i;
if(l < a.size() && a[l] < a[i])
minimum = l;
if(r < a.size() && a[r] < a[minimum])
minimum = r;
if(minimum != i)
{
T temp = a[i];
a[i] = a[minimum];
a[minimum] = temp;
min_heapify(a, minimum);
}
}
}
|