forked from Dipak3007/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.c
More file actions
55 lines (48 loc) · 966 Bytes
/
MaxHeap.c
File metadata and controls
55 lines (48 loc) · 966 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
48
49
50
51
52
53
54
55
#include<stdio.h>
#include<math.h>
int heapsize,length;
int Parent(int i){
return floor(i/2);
}
int Left(int i){
return 2*i;
}
int Right(int i){
return 2*i+1;
}
void MaxHeapify(int A[],int i){
int l=Left(i);
int r=Right(i);
int largest;
if(l<=heapsize && A[l]>A[i])
largest=l;
else
largest=i;
if(r<=heapsize && A[r]>A[largest])
largest=r;
if(largest!=i){
int temp=A[i];
A[i]=A[largest];
A[largest]=temp;
MaxHeapify(A,largest);
}
}
void BuildMaxHeap(int A[]){
heapsize=length;
for(int i=floor(length/2);i>0;i--)
MaxHeapify(A,i);
}
int main()
{
printf("Enter size of array : ");
scanf("%d",&length);
int A[length+1];
printf("Enter Array :-\n");
for(int i=1;i<=length;i++)
scanf("%d",&A[i]);
BuildMaxHeap(A);
printf("\nMaxHeap :-\n");
for(int i=1;i<=length;i++)
printf("%d ",A[i]);
return 0;
}