-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMin-Heap.cpp
50 lines (44 loc) · 899 Bytes
/
Min-Heap.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
// Min-Heap
#include <bits/stdc++.h>
using namespace std;
void heapify(int arr[], int n, int ind){
int smallest = ind;
int left = 2 * ind + 1;
int right = 2 * ind + 2;
if(left < n && arr[left] < arr[smallest]){
smallest = left;
}
if(right < n && arr[right] < arr[smallest]){
smallest = right;
}
if(smallest != ind){
swap(arr[ind], arr[smallest]);
heapify(arr, n, smallest);
}
}
int extract_min(int a[], int &n){
if(n < 1){
return -1;
}
int mini = a[0];
a[0] = a[n - 1];
n--;
heapify(a, n, 0);
return mini;
}
int main()
{
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; ++i){
cin >> a[i];
}
for(int i = (n-1)/2; i >= 0; --i){
heapify(a, n, i);
}
for(int i = 0; i < n; ++i){
cout << extract_min(a, n) << " ";
}
return 0;
}