forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryMinHeap.cs
294 lines (250 loc) · 8.69 KB
/
BinaryMinHeap.cs
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
using System;
using System.Collections.Generic;
using DataStructures.Common;
using DataStructures.Lists;
namespace DataStructures.Heaps
{
/// <summary>
/// Minimum Heap Data Structure.
/// </summary>
public class BinaryMinHeap<T> : IMinHeap<T> where T : IComparable<T>
{
/// <summary>
/// Instance Variables.
/// _collection: The list of elements. Implemented as an array-based list with auto-resizing.
/// </summary>
private ArrayList<T> _collection { get; set; }
private Comparer<T> _heapComparer = Comparer<T>.Default;
/// <summary>
/// CONSTRUCTORS
/// </summary>
public BinaryMinHeap() : this(0, null) { }
public BinaryMinHeap(Comparer<T> comparer) : this(0, comparer) { }
public BinaryMinHeap(int capacity, Comparer<T> comparer)
{
_collection = new ArrayList<T>(capacity);
_heapComparer = comparer ?? Comparer<T>.Default;
}
/// <summary>
/// Builds a min heap from the inner array-list _collection.
/// </summary>
private void _buildMinHeap()
{
int lastIndex = _collection.Count - 1;
int lastNodeWithChildren = (lastIndex / 2);
for (int node = lastNodeWithChildren; node >= 0; node--)
{
_minHeapify(node, lastIndex);
}
}
/// <summary>
/// Private Method. Used to restore heap condition after insertion
/// </summary>
private void _siftUp(int nodeIndex)
{
int parent = (nodeIndex - 1) / 2;
while (_heapComparer.Compare(_collection[nodeIndex], _collection[parent]) < 0)
{
_collection.Swap(parent, nodeIndex);
nodeIndex = parent;
parent = (nodeIndex - 1) / 2;
}
}
/// <summary>
/// Private Method. Used in Building a Min Heap.
/// </summary>
/// <typeparam name="T">Type of Heap elements</typeparam>
/// <param name="nodeIndex">The node index to heapify at.</param>
/// <param name="lastIndex">The last index of collection to stop at.</param>
private void _minHeapify(int nodeIndex, int lastIndex)
{
// assume that the subtrees left(node) and right(node) are max-heaps
int left = (nodeIndex * 2) + 1;
int right = left + 1;
int smallest = nodeIndex;
// If collection[left] < collection[nodeIndex]
if (left <= lastIndex && _heapComparer.Compare(_collection[left], _collection[nodeIndex]) < 0)
smallest = left;
// If collection[right] < collection[smallest]
if (right <= lastIndex && _heapComparer.Compare(_collection[right], _collection[smallest]) < 0)
smallest = right;
// Swap and heapify
if (smallest != nodeIndex)
{
_collection.Swap(nodeIndex, smallest);
_minHeapify(smallest, lastIndex);
}
}
/// <summary>
/// Returns the number of elements in heap
/// </summary>
public int Count
{
get { return _collection.Count; }
}
/// <summary>
/// Checks whether this heap is empty
/// </summary>
public bool IsEmpty
{
get { return (_collection.Count == 0); }
}
/// <summary>
/// Gets or sets the at the specified index.
/// </summary>
/// <param name="index">Index.</param>
public T this[int index]
{
get
{
if (index < 0 || index > this.Count || this.Count == 0)
{
throw new IndexOutOfRangeException();
}
return _collection[index];
}
set
{
if (index < 0 || index >= this.Count)
{
throw new IndexOutOfRangeException();
}
_collection[index] = value;
if (index != 0 && _heapComparer.Compare(_collection[index], _collection[(index - 1) / 2]) < 0) // less than or equal to min
_siftUp(index);
else
_minHeapify(index, _collection.Count - 1);
}
}
/// <summary>
/// Heapifies the specified newCollection. Overrides the current heap.
/// </summary>
/// <param name="newCollection">New collection.</param>
public void Initialize(IList<T> newCollection)
{
if (newCollection.Count > 0)
{
// Reset and reserve the size of the newCollection
_collection = new ArrayList<T>(newCollection.Count);
// Copy the elements from the newCollection to the inner collection
for (int i = 0; i < newCollection.Count; ++i)
{
_collection.InsertAt(newCollection[i], i);
}
// Build the heap
_buildMinHeap();
}
}
/// <summary>
/// Adding a new key to the heap.
/// </summary>
/// <param name="heapKey">Heap key.</param>
public void Add(T heapKey)
{
_collection.Add(heapKey);
if (!IsEmpty)
{
_siftUp(_collection.Count - 1);
}
}
/// <summary>
/// Find the minimum node of a min heap.
/// </summary>
/// <returns>The minimum.</returns>
public T Peek()
{
if (IsEmpty)
{
throw new Exception("Heap is empty.");
}
return _collection.First;
}
/// <summary>
/// Removes the node of minimum value from a min heap.
/// </summary>
public void RemoveMin()
{
if (IsEmpty)
{
throw new Exception("Heap is empty.");
}
int min = 0;
int last = _collection.Count - 1;
_collection.Swap(min, last);
_collection.RemoveAt(last);
last--;
_minHeapify(0, last);
}
/// <summary>
/// Returns the node of minimum value from a min heap after removing it from the heap.
/// </summary>
/// <returns>The min.</returns>
public T ExtractMin()
{
var min = Peek();
RemoveMin();
return min;
}
/// <summary>
/// Clear this heap.
/// </summary>
public void Clear()
{
if (IsEmpty)
{
throw new Exception("Heap is empty.");
}
_collection.Clear();
}
/// <summary>
/// Rebuilds the heap.
/// </summary>
public void RebuildHeap()
{
_buildMinHeap();
}
/// <summary>
/// Returns an array version of this heap.
/// </summary>
public T[] ToArray()
{
return _collection.ToArray();
}
/// <summary>
/// Returns a list version of this heap.
/// </summary>
public List<T> ToList()
{
return _collection.ToList();
}
/// <summary>
/// Union two heaps together, returns a new min-heap of both heaps' elements,
/// ... and then destroys the original ones.
/// </summary>
public BinaryMinHeap<T> Union(ref BinaryMinHeap<T> firstMinHeap, ref BinaryMinHeap<T> secondMinHeap)
{
if (firstMinHeap == null || secondMinHeap == null)
throw new ArgumentNullException("Null heaps are not allowed.");
// Create a new heap with reserved size.
int size = firstMinHeap.Count + secondMinHeap.Count;
var newHeap = new BinaryMinHeap<T>(size, Comparer<T>.Default);
// Insert into the new heap.
while (firstMinHeap.IsEmpty == false)
newHeap.Add(firstMinHeap.ExtractMin());
while (secondMinHeap.IsEmpty == false)
newHeap.Add(secondMinHeap.ExtractMin());
// Destroy the two heaps.
firstMinHeap = secondMinHeap = null;
return newHeap;
}
/// <summary>
/// Returns a new max heap that contains all elements of this heap.
/// </summary>
public IMaxHeap<T> ToMaxHeap()
{
BinaryMaxHeap<T> newMaxHeap = new BinaryMaxHeap<T>(this.Count, this._heapComparer);
newMaxHeap.Initialize(this._collection.ToArray());
return newMaxHeap;
}
}
}