-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpiramidal-sort.cpp
More file actions
72 lines (65 loc) · 1.21 KB
/
Copy pathpiramidal-sort.cpp
File metadata and controls
72 lines (65 loc) · 1.21 KB
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
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> a;
void siftUp(int v){
while(v) {
if(a[v] > a[(v - 1) / 2]) {
swap(a[v], a[(v - 1) / 2]);
v = (v - 1) / 2;
}
else
break;
}
}
void siftDown(int v, int n) {
while(2 * v + 1 < n) {
int l = 2 * v + 1;
int r = 2 * v + 2;
int j = l;
if(r < n && a[r] > a[l]) {
j = r;
}
if(a[v] > a[j]) {
break;
}
swap(a[v], a[j]);
v = j;
}
}
void build(int my_sz) {
for(int i = my_sz / 2; i >= 0; i--){
siftDown(i, my_sz);
}
}
void sort_(){
build(a.size());
int sz = a.size();
int my_sz = sz;
for(int i = 0; i < sz - 1; i++){
swap(a[0], a[sz - i - 1]);
my_sz--;
siftDown(0, my_sz);
}
}
void push(int x){
a.push_back(x);
siftUp((int)a.size() - 1);
}
int main()
{
freopen("sort.in", "r", stdin);
freopen("sort.out", "w", stdout);
int n;
cin >> n;
for(int i = 0; i < n; i++){
int x;
cin >> x;
push(x);
}
sort_();
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
}