Skip to content

Commit 88f8d75

Browse files
committed
Replace rebuilding heap after inserting new element by method that move a node up in the tree, as long as needed
1 parent f646ffd commit 88f8d75

File tree

2 files changed

+34
-14
lines changed

2 files changed

+34
-14
lines changed

DataStructures/Heaps/BinaryMaxHeap.cs

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,20 @@ private void _buildMaxHeap()
4444
}
4545
}
4646

47+
/// <summary>
48+
/// Private Method. Used to restore heap condition after insertion
49+
/// </summary>
50+
private void _siftUp(int nodeIndex)
51+
{
52+
int parent = (nodeIndex - 1) / 2;
53+
while (_heapComparer.Compare(_collection[nodeIndex], _collection[parent]) > 0)
54+
{
55+
_collection.Swap(parent, nodeIndex);
56+
nodeIndex = parent;
57+
parent = (nodeIndex - 1) / 2;
58+
}
59+
}
60+
4761
/// <summary>
4862
/// Private Method. Used in Building a Max Heap.
4963
/// </summary>
@@ -144,14 +158,10 @@ public void Initialize(IList<T> newCollection)
144158
/// </summary>
145159
public void Add(T heapKey)
146160
{
147-
if (IsEmpty)
161+
_collection.Add(heapKey);
162+
if (!IsEmpty)
148163
{
149-
_collection.Add(heapKey);
150-
}
151-
else
152-
{
153-
_collection.Add(heapKey);
154-
_buildMaxHeap();
164+
_siftUp(_collection.Count - 1);
155165
}
156166
}
157167

DataStructures/Heaps/BinaryMinHeap.cs

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,20 @@ private void _buildMinHeap()
4545
}
4646
}
4747

48+
/// <summary>
49+
/// Private Method. Used to restore heap condition after insertion
50+
/// </summary>
51+
private void _siftUp(int nodeIndex)
52+
{
53+
int parent = (nodeIndex - 1) / 2;
54+
while (_heapComparer.Compare(_collection[nodeIndex], _collection[parent]) < 0)
55+
{
56+
_collection.Swap(parent, nodeIndex);
57+
nodeIndex = parent;
58+
parent = (nodeIndex - 1) / 2;
59+
}
60+
}
61+
4862
/// <summary>
4963
/// Private Method. Used in Building a Min Heap.
5064
/// </summary>
@@ -151,14 +165,10 @@ public void Initialize(IList<T> newCollection)
151165
/// <param name="heapKey">Heap key.</param>
152166
public void Add(T heapKey)
153167
{
154-
if (IsEmpty)
168+
_collection.Add(heapKey);
169+
if (!IsEmpty)
155170
{
156-
_collection.Add(heapKey);
157-
}
158-
else
159-
{
160-
_collection.Add(heapKey);
161-
_buildMinHeap();
171+
_siftUp(_collection.Count - 1);
162172
}
163173
}
164174

0 commit comments

Comments
 (0)