-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.cpp
More file actions
47 lines (42 loc) · 854 Bytes
/
Copy pathheap.cpp
File metadata and controls
47 lines (42 loc) · 854 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
#include <bits/stdc++.h>
using namespace std;
void heapify(int arr[], int n, int i)
{
int c1 = 2 * i + 1, c2 = 2 * i + 2, max = i;
if (c1 < n && arr[c1] > arr[max])
max = c1;
if (c2 < n && arr[c2] > arr[max])
max = c2;
if (max != i)
{
int t = arr[i];
arr[i] = arr[max];
arr[max] = t;
heapify(arr, n, max);
}
}
void buildHeap(int arr[], int n)
{
for (int i = n / 2; i >= 0; --i)
heapify(arr, n, i);
}
void printarr(int arr[], int n)
{
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; ++i)
cin >> arr[i];
printarr(arr, n);
buildHeap(arr, n);
printarr(arr, n);
return 0;
}