-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinHeap.cpp
118 lines (102 loc) · 2.43 KB
/
MinHeap.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
/*
Build a min heap class
*/
#include<iostream>
using namespace std;
class minHeap
{
private:
int* h;
int maxSize, currHeapSize;
void bubble_up(int i)
{
int parent = (i - 1) / 2;
while (i > 0 && h[i] < h[parent])
{
swap(h[i], h[parent]);
i = parent;
parent = (i - 1) / 2;
}
}
void bubble_down(int i)
{
int left_child = 2 * i + 1;
int right_child = 2 * i + 2;
int smallest = i;
if (left_child < currHeapSize && h[left_child] < h[smallest])
{
smallest = left_child;
}
if (right_child < currHeapSize && h[right_child] < h[smallest])
{
smallest = right_child;
}
if (smallest != i)
{
swap(h[i], h[smallest]);
bubble_down(smallest);
}
}
public:
minHeap(int capacity = 10) : h(new int[capacity]), maxSize(capacity), currHeapSize(0) {}
void buildMinHeap()
{
for (int i = currHeapSize / 2 - 1; i >= 0; --i)
{
bubble_down(i);
}
}
void insertASingleValueInHeap(const int& x)
{
if (currHeapSize == maxSize)
{
cout << "Heap is full. Cannot insert more elements." << endl;
return;
}
h[currHeapSize] = x;
bubble_up(currHeapSize);
++currHeapSize;
}
bool isEmpty() const
{
return currHeapSize == 0;
}
const int& getMin() const
{
if (isEmpty())
{
cout << "Heap is empty. No minimum value to retrieve." << endl;
return h[0];
}
return h[0];
}
};
void heapSort(int arr[], int N)
{
minHeap mh(N);
for (int i = 0; i < N; ++i)
{
mh.insertASingleValueInHeap(arr[i]);
}
for (int i = 0; i < N; i++)
{
arr[i] = mh.getMin();
mh.h[0] = mh.h[mh.currHeapSize - 1];
mh.currHeapSize--;
mh.bubble_down(0);
}
}
int main() {
minHeap myHeap(10);
int a;
myHeap.insertSingleValueInHeap(4);
myHeap.insertSingleValueInHeap(10);
myHeap.insertSingleValueInHeap(3);
myHeap.insertSingleValueInHeap(5);
myHeap.insertSingleValueInHeap(1);
myHeap.getMin(a);
cout << "Minimum value in the heap: " << a << endl;
myHeap.getMin(a);
system("pause");
return 0;
}