File tree Expand file tree Collapse file tree 2 files changed +34
-14
lines changed Expand file tree Collapse file tree 2 files changed +34
-14
lines changed Original file line number Diff line number Diff line change @@ -44,6 +44,20 @@ private void _buildMaxHeap()
44
44
}
45
45
}
46
46
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
+
47
61
/// <summary>
48
62
/// Private Method. Used in Building a Max Heap.
49
63
/// </summary>
@@ -144,14 +158,10 @@ public void Initialize(IList<T> newCollection)
144
158
/// </summary>
145
159
public void Add ( T heapKey )
146
160
{
147
- if ( IsEmpty )
161
+ _collection . Add ( heapKey ) ;
162
+ if ( ! IsEmpty )
148
163
{
149
- _collection . Add ( heapKey ) ;
150
- }
151
- else
152
- {
153
- _collection . Add ( heapKey ) ;
154
- _buildMaxHeap ( ) ;
164
+ _siftUp ( _collection . Count - 1 ) ;
155
165
}
156
166
}
157
167
Original file line number Diff line number Diff line change @@ -45,6 +45,20 @@ private void _buildMinHeap()
45
45
}
46
46
}
47
47
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
+
48
62
/// <summary>
49
63
/// Private Method. Used in Building a Min Heap.
50
64
/// </summary>
@@ -151,14 +165,10 @@ public void Initialize(IList<T> newCollection)
151
165
/// <param name="heapKey">Heap key.</param>
152
166
public void Add ( T heapKey )
153
167
{
154
- if ( IsEmpty )
168
+ _collection . Add ( heapKey ) ;
169
+ if ( ! IsEmpty )
155
170
{
156
- _collection . Add ( heapKey ) ;
157
- }
158
- else
159
- {
160
- _collection . Add ( heapKey ) ;
161
- _buildMinHeap ( ) ;
171
+ _siftUp ( _collection . Count - 1 ) ;
162
172
}
163
173
}
164
174
You can’t perform that action at this time.
0 commit comments