-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinHeap.cpp
More file actions
188 lines (156 loc) · 3.21 KB
/
MinHeap.cpp
File metadata and controls
188 lines (156 loc) · 3.21 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#include <iostream>
using namespace std;
const int heapsize = 7;
int heap[heapsize];
static int n = 0;
class Node
{
friend class Tree;
int data;
Node *left;
Node *right;
};
class Tree
{ public:
Node *root =0;
void insertheap(int data);
int deleteheap();
bool HeapEmpty();
bool HeapFull();
void Printheap();
void insert(int key);
int LevelTest(Node *root);
};
int Tree::LevelTest(Node *root)
{
int count = 0;
int level = 0;
if(n == 0) return 0;
for (int i = 0; i < n; i++){
if (heap[i] =!NULL){
count++;
}
}
level = count/2 ;
cout<<"LevelTest : ";
cout<< level<<endl;
}
bool Tree::HeapEmpty(){
if ( n == 0 ){
return true;
}
else
{
return false;
}
}
bool Tree::HeapFull(){
if (n == heapsize){
return true;
}
else
{
return false;
}
}
void Tree::insertheap(int data){
int i;
if (HeapFull()){
cout<<"heap is full"<<endl;
exit(1);
}
i = ++n;
while( (i!=1) && (data < heap[i/2]) ){
heap[i] = heap[i/2];
i = i/2;
}
heap[i] =data;
}
int Tree::deleteheap(){
int parent;
int child;
int temp;
int item;
item = heap[0];
temp = heap[n--];
parent =1;
child = 2;
while(child <= n){
if (child < n && heap[child] > heap[child+1]) {
child++;
}
if (temp < heap[child]){
// cout<<heap[child]<<endl;
break;
}
heap[parent] = heap[child];
parent = child;
child = child *2;
}
heap[parent] =temp;
return item;
}
void Tree::Printheap(){
if (n == 0){
cout<< "heap is empty"<<endl;
}
else
{
// cout<<heap[0] << " ";
for (int i = 1; i<n+1; i++){
cout<<heap[i]<<" ";
}
}
// cout<<heap[n]<<endl;
}
int main()
{
Tree t;
int menuNum;
int num;
while(1){
cout<<"1.Insert 2.Delete 3.Empty 4.Full 5.levelTest 6. Quit 7.Print"<<endl;
cin >> menuNum;
switch(menuNum)
{
case 1:
cout<< "enter number to insert : ";
cin >> num;
t.insertheap(num);
break;
case 2:
t.deleteheap();
t.Printheap();
cout<<endl;
break;
case 3:
if (t.HeapEmpty()) {
cout<< "heap is empty"<<endl;
}
else
{
cout<<"heap is not empty"<<endl;
}
break;
case 4:
if (t.HeapFull()){
cout<< "heap is full"<<endl;
}
else
{
cout<< "heap is not full"<<endl;
}
break;
case 5:
t.LevelTest(t.root);
break;
case 6:
exit(1);
break;
case 7:
t.Printheap();
cout<<endl;
}
}
return 0;
}