-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmin_heap.cpp
More file actions
107 lines (94 loc) · 2.04 KB
/
min_heap.cpp
File metadata and controls
107 lines (94 loc) · 2.04 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
#include <bits/stdc++.h>
using namespace std;
class minHeap
{
public:
int *arr; // pointer to array of elements in heap
int capacity; // maximum possible size of min heap
int heap_size; // current number of elements in min heap
minHeap(int cap)
{
capacity = cap;
heap_size = 0;
arr = new int[capacity];
}
int height()
{
return ceil(log2(heap_size + 1)) - 1;
}
int parent(int i)
{
return (i - 1) / 2;
}
int left(int i)
{
return (2 * i) + 1;
}
int right(int i)
{
return (2 * i) + 2;
}
void insert(int k)
{
if (heap_size == capacity)
{
cout << "Overflow" << "\n";
return;
}
heap_size++;
int i = heap_size - 1;
arr[i] = k;
while (i != 0 && arr[parent(i)] > arr[i])
{
swap(arr[parent(i)], arr[i]);
i = parent(i);
}
}
void minHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && arr[l] < arr[i])
smallest = l;
if (r < heap_size && arr[r] < arr[smallest])
smallest = r;
if (smallest != i)
{
swap(arr[i], arr[smallest]);
minHeapify(smallest);
}
}
int extraction() // extract minimum element from heap and delete it from heap
{
if (heap_size <= 0) return INT_MAX;
if (heap_size == 1)
{
heap_size--;
return arr[0];
}
int root = arr[0];
arr[0] = arr[heap_size - 1];
heap_size--;
minHeapify(0);
return root;
}
void decreaseKey(int i, int new_val)
{
arr[i] = new_val;
while (i != 0 && arr[parent(i)] > arr[i])
{
swap(arr[i], arr[parent(i)]);
i = parent(i);
}
}
void deleteKey(int i)
{
decreaseKey(i, INT_MIN);
extraction();
}
};
main()
{
minHeap obj1(5);
}