TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
binaryheap.cpp
Go to the documentation of this file.
1
5#include <climits>
6#include <iostream>
7#include <utility>
8
10class MinHeap {
11 int *harr;
14
15 public:
19 explicit MinHeap(int cap) {
20 heap_size = 0;
21 capacity = cap;
22 harr = new int[cap];
23 }
24
26 void MinHeapify(int);
27
28 int parent(int i) { return (i - 1) / 2; }
29
31 int left(int i) { return (2 * i + 1); }
32
34 int right(int i) { return (2 * i + 2); }
35
37 int extractMin();
38
40 void decreaseKey(int i, int new_val);
41
43 int getMin() { return harr[0]; }
44
46 void deleteKey(int i);
47
49 void insertKey(int k);
50
51 ~MinHeap() { delete[] harr; }
52};
53
54// Inserts a new key 'k'
55void MinHeap::insertKey(int k) {
56 if (heap_size == capacity) {
57 std::cout << "\nOverflow: Could not insertKey\n";
58 return;
59 }
60
61 // First insert the new key at the end
62 heap_size++;
63 int i = heap_size - 1;
64 harr[i] = k;
65
66 // Fix the min heap property if it is violated
67 while (i != 0 && harr[parent(i)] > harr[i]) {
68 std::swap(harr[i], harr[parent(i)]);
69 i = parent(i);
70 }
71}
72
76void MinHeap::decreaseKey(int i, int new_val) {
77 harr[i] = new_val;
78 while (i != 0 && harr[parent(i)] > harr[i]) {
79 std::swap(harr[i], harr[parent(i)]);
80 i = parent(i);
81 }
82}
83
84// Method to remove minimum element (or root) from min heap
86 if (heap_size <= 0)
87 return INT_MAX;
88 if (heap_size == 1) {
89 heap_size--;
90 return harr[0];
91 }
92
93 // Store the minimum value, and remove it from heap
94 int root = harr[0];
95 harr[0] = harr[heap_size - 1];
96 heap_size--;
97 MinHeapify(0);
98
99 return root;
100}
101
106 decreaseKey(i, INT_MIN);
107 extractMin();
108}
109
114 int l = left(i);
115 int r = right(i);
116 int smallest = i;
117 if (l < heap_size && harr[l] < harr[i])
118 smallest = l;
119 if (r < heap_size && harr[r] < harr[smallest])
120 smallest = r;
121 if (smallest != i) {
122 std::swap(harr[i], harr[smallest]);
123 MinHeapify(smallest);
124 }
125}
126
127// Driver program to test above functions
128int main() {
129 MinHeap h(11);
130 h.insertKey(3);
131 h.insertKey(2);
132 h.deleteKey(1);
133 h.insertKey(15);
134 h.insertKey(5);
135 h.insertKey(4);
136 h.insertKey(45);
137 std::cout << h.extractMin() << " ";
138 std::cout << h.getMin() << " ";
139 h.decreaseKey(2, 1);
140 std::cout << h.getMin();
141 return 0;
142}
MinHeap(int cap)
int getMin()
int * harr
pointer to array of elements in heap
void deleteKey(int i)
int extractMin()
int capacity
maximum possible size of min heap
void decreaseKey(int i, int new_val)
int left(int i)
void MinHeapify(int)
int right(int i)
int heap_size
Current number of elements in min heap.
void insertKey(int k)
int main()
Main function.
int h(int key)