-
Notifications
You must be signed in to change notification settings - Fork 2
/
insertion_deletion.cpp
82 lines (68 loc) · 1.57 KB
/
insertion_deletion.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
#include <iostream>
using namespace std;
class Heap {
public:
int heap[100];
int size = 0;
Heap() {
heap[0] = -1;
size = 0;
}
void insert(int val) {
size = size + 1;
int index = size;
heap[index] = val;
while(index > 1) {
int parent = index / 2;
if(heap[parent] < heap[index]) {
swap(heap[parent], heap[index]);
index = parent;
}
else {
return;
}
}
}
void delete_root() {
if(size == 0) {
cout << "Heap is empty!" << endl;
return;
}
heap[1] = heap[size];
size = size-1;
int i = 1;
while(i < size) {
int leftIndex = 2 * i;
int rightIndex = 2 * i + 1;
if(leftIndex < size && heap[i] < heap[leftIndex]) {
swap(heap[i], heap[leftIndex]);
i = leftIndex;
}
else if(rightIndex < size && heap[i] < heap[rightIndex]) {
swap(heap[i], heap[rightIndex]);
i = rightIndex;
}
else {
return;
}
}
}
void print() {
for(int i = 1; i <= size; i++) {
cout << heap[i] << " ";
}
cout << endl;
}
};
int main() {
Heap heap;
heap.insert(125);
heap.insert(165);
heap.insert(45);
heap.insert(65);
heap.insert(155);
heap.print();
heap.delete_root();
heap.print();
return 0;
}