Skip to content

Commit 0b48f61

Browse files
authored
Create HeapSort
1 parent a8a6550 commit 0b48f61

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Sorting/HeapSort/C++/HeapSort

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
void bottom_up(int heap[], int n){
2+
int k,v, i, j;
3+
bool check;
4+
for(i=n/2;i>=1;i--){
5+
k = i;
6+
check = false;
7+
v = heap[i];
8+
while(!check && (2*k)<=n){
9+
j = 2*k;
10+
if(j<n && heap[j]<heap[j+1]){
11+
j++;
12+
}
13+
if(v>=heap[j]){
14+
check = true;
15+
}
16+
else{
17+
heap[k] = heap[j];
18+
k = j;
19+
}
20+
}
21+
heap[k] = v;
22+
}
23+
}
24+
25+
void heap_sort(int heap[], int n){
26+
if(n>1){
27+
bottom_up(heap, n);
28+
int aux = heap[n];
29+
heap[n] = heap[1];
30+
heap[1] = aux;
31+
heap_sort(heap, n-1);
32+
}
33+
}
34+
int main() {
35+
ios::sync_with_stdio(0);
36+
cin.tie(0);
37+
38+
int vet[100000], vetn=0;
39+
cin >> vetn;
40+
int i;
41+
for(i=0;i<vetn;i++){
42+
cin >> vet[i];
43+
}
44+
45+
heap_sort(vet, vetn);
46+
47+
for(i=0;i<vetn;i++){
48+
cout << vet[i] << " ";
49+
}
50+
return 0;
51+
}

0 commit comments

Comments
 (0)