-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinHeap.cpp
118 lines (94 loc) · 1.94 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
#include "stdafx.h"
#include "MinHeap.h"
MinHeap::MinHeap(int* array, int length) : _vector(length)
{
for (int i = 0; i < length; ++i)
{
_vector[i] = array[i];
}
Heapify();
}
MinHeap::MinHeap(const vector<int>& vector) : _vector(vector)
{
Heapify();
}
MinHeap::MinHeap()
{
}
void MinHeap::Heapify()
{
int length = active_vector_size;
for (int i = length - 1; i >= 0; --i)
{
BubbleDown(i);
}
}
void MinHeap::BubbleDown(int index)
{
int length = active_vector_size;
int leftChildIndex = 2 * index + 1;
int rightChildIndex = 2 * index + 2;
if (leftChildIndex >= length)
return; //index is a leaf
int minIndex = index;
if (_vector[index] > _vector[leftChildIndex])
{
minIndex = leftChildIndex;
}
if ((rightChildIndex < length) && (_vector[minIndex] > _vector[rightChildIndex]))
{
minIndex = rightChildIndex;
}
if (minIndex != index)
{
//need to swap
int temp = _vector[index];
_vector[index] = _vector[minIndex];
_vector[minIndex] = temp;
BubbleDown(minIndex);
}
}
void MinHeap::BubbleUp(int index)
{
if (index == 0)
return;
int parentIndex = (index - 1) / 2;
if (_vector[parentIndex] > _vector[index])
{
int temp = _vector[parentIndex];
_vector[parentIndex] = _vector[index];
_vector[index] = temp;
BubbleUp(parentIndex);
}
}
void MinHeap::Insert(int newValue)
{
if (_vector.size() > 0)
{
int length = active_vector_size;
_vector[length] = newValue;
active_vector_size++;
BubbleUp(length);
}
else
_vector.push_back(newValue);
active_vector_size++;
}
int MinHeap::GetMin()
{
if (_vector.size() > 0)
return _vector[0];
else
return -1;
}
void MinHeap::DeleteMin()
{
int length = active_vector_size;
if (length == 0)
return;
_vector[0] = _vector[length - 1];
//_vector.pop_back();
_vector.erase(_vector.begin() + (length-1));
active_vector_size--;
BubbleDown(0);
}