-
Notifications
You must be signed in to change notification settings - Fork 3
/
Heap.cpp
148 lines (142 loc) · 2.59 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
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
// Implement heap Data Structure
#include<iostream>
#include<math.h>
# define SIZE 10
int extract_max();
int increase_key(int, int);
void insert(int);
void heapify(int);
int heap[SIZE];
int CS = 0; //Current Size
using namespace std;
int main()
{
int i;
do
{
cout << "\n[1] Extract Max";
cout << "\n[2] Increase Key";
cout << "\n[3] Insert";
cout << "\n[4] Show Heap";
cout << "\n[0] Exit\n";
cin >> i;
if(i == 1)
{
if(CS != 0)
{
int t;
t = extract_max();
cout << "\nMaximum Value : " << t;
}
else
{
cout << "\nHeap is Empty";
}
}
else if(i == 2)
{
int t1, t2;
cout << "\nEnter the position of the key to be Increased :\n";
cin >> t1;
cout << "\nEnter the new Increased Value :\n";
cin >> t2;
int r = increase_key(t1, t2);
if(r != 0)
{
cout << "\nKey Value Increased";
}
}
else if(i == 3)
{
int k;
cout << "\nPlease Enter the new Key :\n";
cin >> k;
insert(k);
}
else if(i == 4)
{
for(int i = 0; i < CS; i++)
{
cout << heap[i] << " ";
}
}
}while(i != 0);
}
int extract_max()
{
int t;
t = heap[0];
heap[0] = heap[CS - 1];
CS--;
heapify(0);
return t;
}
int increase_key(int i, int k)
{
int r = 1;
if(heap[i] < k)
{
heap[i] = k;
while(i > 0)
{
int p = floor((i-1)/2); //Parent of i
if(heap[p] < heap[i])
{
int t;
t = heap[p];
heap[p] = heap[i];
heap[i] = t;
i = p;
}
else
{
break;
}
}
}
else
{
cout << "\nNew key is smaller than the Current key";
r = 0;
}
return r;
}
void insert(int k)
{
CS++;
if(CS <= SIZE)
{
increase_key(CS - 1, k);
cout << "\nValue Inserted";
}
else
{
cout << "\nHeap is Full";
}
}
void heapify(int i)
{
int l,r, largest;
l = 2 * i + 1;
r = 2 * i + 2;
if(l < CS || r < CS)
{
if(heap[l] > heap[r])
{
largest = l;
}
else
{
largest = r;
}
if(heap[largest] > heap[i])
{
int t;
t = heap[largest];
heap[largest] = heap[i];
heap[i] = t;
i = largest;
heapify(i);
}
}
}