-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapsort.h
More file actions
74 lines (37 loc) · 783 Bytes
/
Copy pathheapsort.h
File metadata and controls
74 lines (37 loc) · 783 Bytes
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
#pragma once
inline int Left(int i){
return 2 * i + 1;
}
inline int Right(int i){
return 2 * (i + 1);
}
// O(lg n)
void Heapify(int* a, int n, int i){
int max = i;
if(Left(i) < n && a[Left(i)] > a[i]){
max = Left(i);
}
if(Right(i) < n && a[Right(i)] > a[i] && a[Right(i)] > a[Left(i)]){
max = Right(i);
}
if(max != i){
std::swap(a[max],a[i]);
Heapify(a,n,max);
}
}
//nlgn
void BuildMaxHeap(int* a, int n){
int start = n / 2 - 1;
for(int i = start; i >= 0; i--){
Heapify(a,n,i);
}
}
void heapsort(int* a, int n){
BuildMaxHeap(a,n);
std::swap(a[0],a[n-1]);
n--;
for(;n >= 1; n--){
Heapify(a,n,0);
std::swap(a[0],a[n-1]);
}
}