-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.cpp
More file actions
64 lines (61 loc) · 1.01 KB
/
Heap.cpp
File metadata and controls
64 lines (61 loc) · 1.01 KB
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
#include <iostream>
using namespace std;
int a[100],n;
void upheap(int pos)
{
int i=pos;
while(i>1 && a[pos]>a[pos/2])
{
swap(a[pos],a[pos/2]);
pos/=2;
}
}
void add(int ele)
{
a[++n]=ele;
upheap(n);
}
void downheap(int pos)
{
int larger=pos;
if(pos*2<=n && a[pos*2]>a[larger])
larger=pos*2;
if((pos*2+1)<=n && a[pos*2+1]>a[larger])
larger=pos*2+1;
if(pos!=larger)
{
swap(a[pos],a[larger]);
downheap(larger);
}
}
int maxdel()
{
int m=a[1];
a[1]=a[n--];
downheap(1);
return m;
}
int main()
{
int ele;
cin>>n;
cout<<"Enter array";
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
cout<<"Element to insert :";
cin>>ele;
add(ele);
cout<<endl;
for(int i=1;i<=n;i++)
{
cout<<a[i]<<" ";
}
cout<<"Maximum ele"<<maxdel()<<endl;
for(int i=1;i<=n;i++)
{
cout<<a[i]<<" ";
}
return 0;
}