forked from zeetkumar/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuild Heap.cpp
More file actions
47 lines (37 loc) · 751 Bytes
/
Build Heap.cpp
File metadata and controls
47 lines (37 loc) · 751 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;
//5,3,2,25,7,17,20,28,4
void maxHeapify(int a[],int n,int index){
int l,r,largest;
l=(index+1)*2-1;
r=(index+1)*2;
if(l<n && a[l]>a[index]){
largest=l;
}
else{
largest=index;
}
if(r<n && a[r]>a[largest]){
largest=r;
}
if(largest!=index){
int temp=a[index];
a[index]=a[largest];
a[largest]=temp;
maxHeapify(a,n,largest);
}
}
void buildHeap(int a[],int n){
for(int i=n/2;i>=0;i--){
maxHeapify(a,n,i);
}
}
int main(){
int a[]={65,3,22,25,27,17,20,8,4};
int n=sizeof(a)/sizeof(int);
buildHeap(a,n);
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}