-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlec9_1.cpp
More file actions
93 lines (78 loc) Β· 1.96 KB
/
Copy pathlec9_1.cpp
File metadata and controls
93 lines (78 loc) Β· 1.96 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
#include <iostream>
#include <cmath>
using namespace std;
class MinHeap {
int* arr; // pointer to the array
int size; // current number of elements in the heap
int total_size; // maximum capacity of the heap
public:
MinHeap(int n) {
arr = new int[n];
size = 0; // start with an empty heap
total_size = n; // maximum capacity
}
// inserting a new node
void insert(int value) {
if (size == total_size) {
cout << "Heap overflow" << endl;
return;
}
arr[size] = value;
int index = size;
size++;
// Step-up heapify
while (index > 0 && arr[(index - 1) / 2] > arr[index]) {
swap(arr[(index - 1) / 2], arr[index]);
index = (index - 1) / 2;
}
cout << value << " is inserted" << endl;
}
void Delete() {
if (size == 0) {
cout << "Heap underflow" << endl;
return;
}
cout << arr[0] << " is deleted" << endl;
arr[0] = arr[size - 1];
size--;
if (size > 0) {
Heapify(0);
}
}
void Heapify(int index) {
int smallest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
if (left < size && arr[left] < arr[smallest]) {
smallest = left;
}
if (right < size && arr[right] < arr[smallest]) {
smallest = right;
}
if (smallest != index) {
swap(arr[smallest], arr[index]);
Heapify(smallest);
}
}
void print() {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
~MinHeap() {
delete[] arr; // release memory
}
};
int main() {
MinHeap m(5);
m.insert(10);
m.insert(20);
m.insert(30);
m.insert(40);
m.insert(50);
m.print();
m.Delete();
m.print();
return 0;
}