-
Notifications
You must be signed in to change notification settings - Fork 0
/
(HEAP)MAXCHEAP.cpp
67 lines (62 loc) · 1 KB
/
(HEAP)MAXCHEAP.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
using namespace std;
// INSERT AN ELEMENT IN AN ARRAY IN NEXT FREE SPACE BECAUSE WE HAVE TO MAINTAIN A COMPLETE BINARY TREE ALSO
// MAX HEAP ->EVERY NODE SHOULD HAVE AN ELEMENT GREATER THASN ALL ITS DESCENDENTS
void insert(int a[],int x)
{
int t=a[x],i=x;
while(i>1 && t>a[i/2])
{
a[i]=a[i/2];
i=i/2;
}
a[i]=t;
}
void swap(int *x,int*y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
void deleteheap(int a[],int N)
{
// int x=n;
int val=a[1],t=a[N];
a[1]=a[N];
a[N]=val;
int i=1,j=2*i;
while(j<=N-1 )
{
if(j<N-1 && a[j+1]>a[j])
j++;
if(a[j]>a[i])
{swap(&a[i],&a[j]);
i=j;
j=2*j;
}
else
{
break;
}
}
}
void print(int a[],int n)
{
for(int i=1;i<=n;i++)
cout<<a[i]<<" ";
}
int main()
{
int a[]={0,6,5,2,3,8,4,7,1}, n=8;
for(int i=1;i<=n;i++)
{
insert(a,i);
}
for(int i=n;i>1;i--)
{
deleteheap(a,i);
}
print(a,n);
return 0;
}