Skip to content

Commit a327cae

Browse files
committed
Fix bug. Right positioning element after set element by index
1 parent 88f8d75 commit a327cae

File tree

2 files changed

+8
-10
lines changed

2 files changed

+8
-10
lines changed

DataStructures/Heaps/BinaryMaxHeap.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -124,11 +124,10 @@ public T this[int index]
124124

125125
_collection[index] = value;
126126

127-
if (_heapComparer.Compare(_collection[index], _collection[0]) >= 0) // greater than or equal to max
128-
{
129-
_collection.Swap(0, index);
130-
_buildMaxHeap();
131-
}
127+
if (index != 0 && _heapComparer.Compare(_collection[index], _collection[(index - 1) / 2]) > 0) // greater than or equal to max
128+
_siftUp(index);
129+
else
130+
_maxHeapify(index, _collection.Count - 1);
132131
}
133132
}
134133

DataStructures/Heaps/BinaryMinHeap.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -129,11 +129,10 @@ public T this[int index]
129129

130130
_collection[index] = value;
131131

132-
if (_heapComparer.Compare(_collection[index], _collection[0]) <= 0) // less than or equal to min
133-
{
134-
_collection.Swap(0, index);
135-
_buildMinHeap();
136-
}
132+
if (index != 0 && _heapComparer.Compare(_collection[index], _collection[(index - 1) / 2]) < 0) // less than or equal to min
133+
_siftUp(index);
134+
else
135+
_minHeapify(index, _collection.Count - 1);
137136
}
138137
}
139138

0 commit comments

Comments
 (0)