-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathheap.cpp
More file actions
100 lines (89 loc) · 1.76 KB
/
heap.cpp
File metadata and controls
100 lines (89 loc) · 1.76 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<iostream>
using namespace std;
class Heap{
int arr[20];
int count;
public:
Heap()
{
for(int i=0;i<count;i++)
{
arr[i]=0;
}
}
void add()
{
int j=0;
char choice;
int elem;
int count=0;
do
{
cout<<"Enter the node"<<endl;
cin>>elem;
arr[j]=elem;
insert(arr,j+1);
j++;
count++;
cout<<"Do you want to enter more nodes(y/n)"<<endl;
cin>>choice;
} while (choice=='y');
display();
}
void insert(int a[],int n)
{
int i=n;
int elem=arr[n-1];
if(i!=1)
{
while((i>1)&&(a[(i/2)-1]<elem))
{
a[i-1]=a[(i/2)-1];
i=i/2;
}
a[i-1]=elem;
}
}
void display()
{
for(int i=0;i<count;i++)
{
cout<<arr[i]<<"\t"<<endl;
}
}
void deleteheap(){
char ch;
do{
arr[0]=arr[0]+arr[count-1];
arr[count-1]=arr[0]-arr[count-1];
arr[0]=arr[0]-arr[count-1];
count--;
adjust(count-1,0);
display();
cout << "Do you want to delete more node: (y/n)";
cin >> ch;
} while (ch == 'y');
}
void adjust(int n,int i){
do{
int j=2*i+1;
if((j+1<=n)&&(arr[j+1]>arr[j]))
j++;
if(arr[i]>=arr[j])
break;
else{
arr[i]=arr[i]+arr[j];
arr[j]=arr[i]-arr[j];
arr[i]=arr[i]-arr[j];
i=j;
}
}while(2*i+1<=n);
}
};
int main()
{
Heap h;
h.add();
h.display();
h.deleteheap();
}