-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuildMaxHeap.cpp
More file actions
46 lines (42 loc) · 944 Bytes
/
Copy pathbuildMaxHeap.cpp
File metadata and controls
46 lines (42 loc) · 944 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
#include <bits/stdc++.h>
using namespace std;
#define LEFT(i) ((i+1)<<1) - 1
#define RIGHT(i) (i+1)<<1
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
void heapify(int A[], int i, int n) {
int largest, l, r;
l = LEFT(i);
r = RIGHT(i);
while(l < n) {
if(A[l] > A[i]) largest = l;
else largest = i;
if(r < n && A[r] > A[largest]) largest = r;
if(largest != i) {
swap(&A[i], &A[largest]);
i = largest;
l = LEFT(i);
r = RIGHT(i);
}
else break;
}
}
void maxHeap(int A[], int n) {
for(int i = n/2; i >= 0; i--) {
heapify(A, i, n);
}
}
int main() {
int a[] = {27, 17, 3, 16, 13, 10, 1, 5, 7, 12, 4, 8, 9, 0};
int n = sizeof(a)/sizeof(int);
cout << n << endl;
maxHeap(a, n);
for(int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}