-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap_sort.cpp
134 lines (106 loc) · 1.91 KB
/
heap_sort.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
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
#include <iostream>
#include <vector>
#include <climits>
#include <cassert>
#include "heap_sort.hpp"
#include "my_tools.hpp"
using namespace std;
static int get_parent(int i)
{
return (i-1)/2;
}
static int left_child(int i)
{
return 2*i+1;
}
static int right_child(int i)
{
return 2*i+2;
}
static void max_heapify(vector<int> &a, int i, int heap_size)
{
int left = left_child(i);
int right = right_child(i);
int i_max = i;
if (left < heap_size && a[left] > a[i_max]) {
i_max = left;
}
if (right < heap_size && a[right] > a[i_max]) {
i_max = right;
}
if (i != i_max) {
swap(a[i], a[i_max]);
max_heapify(a, i_max, heap_size);
}
}
static void max_heapify(vector<int> &a, int i)
{
return max_heapify(a, i, a.size());
}
void build_max_heap(vector<int> &a)
{
for (int i = (int)a.size()/2-1; i >= 0; i--) {
max_heapify(a, i);
}
}
int heap_max(const vector<int> &a)
{
return a[0];
}
int heap_pop_max(vector<int> &a)
{
if (a.empty()) {
assert(0);
return 0;
}
int max = a[0];
a[0] = a.back();
a.pop_back();
max_heapify(a, 0);
return max;
}
static void heap_increase_key(vector<int> &a, int i, int key)
{
if (key < a[i]) {
assert(0);
return;
}
a[i] = key;
int parent = get_parent(i);
while (i > 0 && a[parent] < a[i]) {
swap(a[i], a[parent]);
i = parent;
parent = get_parent(i);
}
}
void max_heap_insert(vector<int> &a, int key)
{
a.push_back(-INT_MAX);
heap_increase_key(a, (int)a.size()-1, key);
}
void heap_sort(vector<int> &a)
{
ScopedClock cl(__FUNCTION__);
build_max_heap(a);
for (int i = (int)a.size()-1; i >= 1; i--) {
swap(a[0], a[i]);
max_heapify(a, 0, i);
}
}
void test_heap_sort()
{
for (int i = 0; i < 100; i++) {
int n = rand_int(1, 100000);
vector<int> a(n);
for (int j = 0; j < n; j++) {
a[j] = rand_int(1, 1000);
}
heap_sort(a);
for (int j = 1; j < n; j++) {
if (a[j] < a[j-1]) {
print_vec("sorted: ", a);
assert(0);
}
}
}
}