-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.cpp
90 lines (87 loc) · 1.67 KB
/
heap.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//
// main.cpp
// heap_tree
//
// Created by raghav babbar on 02/02/17.
// Copyright © 2017 raghav babbar. All rights reserved.
//
#include <iostream>
using namespace std;
#define max 20
class heaptree
{int heap[max];
int n;
public:
heaptree()
{n=-1;
}
void insert_item(int);
int delete_head();
void display();
};
void heaptree:: insert_item(int item )
{
n+=1;
if(n>=max)
{cout<<"\n overflow ";
return;
}
heap[n]=item;
int p=n;
int parent=(n-1)/2;
int data=item;
int f=0;
while((parent!=p)&&item>heap[parent])
{ heap[p]=heap[parent];
p=parent;
parent=(p-1)/2;
f=2;}
if(f)
heap[parent]=item;
}
int heaptree::delete_head()
{
int t=heap[0];
heap[0]=heap[n];
n--;
int i=0,temp;
int downi;
while(true)
{downi=i;
if((downi*2+1)<=n&&heap[downi*2+1]>heap[i])
i=downi*2+1;
if((downi*2+2)<=n&&heap[downi*2+2]>heap[i])
i=downi*2+2;
if(downi==i)
break;
temp=heap[downi];
heap[downi]=heap[i];
heap[i]=temp;
}
return t;
}
void heaptree::display()
{
for (int i=0;i<=n;i++) {
cout<<" "<<heap[i];
}
}
int main(int argc, const char * argv[]) {
heaptree h;
while (true) {
cout<<"\n eneter the choice";
int i,tt;
cin>>i;
switch (i) {
case 1:cout<<"\n enter the item";
cin>>tt;
h.insert_item(tt);
break;
case 2:h.display(); break;
case 3:cout<<"deleting element "<<h.delete_head(); break;
default: exit(0);
break;
}
}
return 0;
}