parent
bae9fe4149
commit
1f5071f318
@ -0,0 +1,85 @@ |
||||
namespace MainNamespace.Structure |
||||
{ |
||||
class Heap<T> |
||||
{ |
||||
private List<T> _nodeList; |
||||
|
||||
private Comparer<T> _comparer = Comparer<T>.Default; |
||||
private bool _maxHeap = true; |
||||
private readonly int COMPARER_SIGN = 1; |
||||
|
||||
public bool MaxHeap { get { return _maxHeap; } } |
||||
|
||||
public Heap(bool maxHeap = true) |
||||
{ |
||||
_nodeList = new List<T>(); |
||||
_maxHeap = maxHeap; |
||||
COMPARER_SIGN = maxHeap ? 1 : -1; |
||||
} |
||||
public void Add(T value) |
||||
{ |
||||
_nodeList.Add(value); |
||||
|
||||
// bubble up |
||||
int i = _nodeList.Count - 1; |
||||
while (i > 0) |
||||
{ |
||||
int parent = (i - 1) / 2; |
||||
if (_comparer.Compare(_nodeList[parent], _nodeList[i]) * COMPARER_SIGN >= 0) |
||||
break; |
||||
|
||||
Swap(parent, i); |
||||
i = parent; |
||||
} |
||||
} |
||||
|
||||
public T RemoveOne() |
||||
{ |
||||
if (_nodeList.Count == 0) |
||||
throw new InvalidOperationException(); |
||||
|
||||
T root = _nodeList[0]; |
||||
|
||||
// move last to first and remove last one |
||||
_nodeList[0] = _nodeList[_nodeList.Count - 1]; |
||||
_nodeList.RemoveAt(_nodeList.Count - 1); |
||||
|
||||
int i = 0; |
||||
int last = _nodeList.Count - 1; |
||||
|
||||
// bubble down |
||||
while (i < last) |
||||
{ |
||||
// left child index |
||||
int child = i * 2 + 1; |
||||
|
||||
// use right child if it is bigger |
||||
if (child < last && |
||||
_comparer.Compare(_nodeList[child], _nodeList[child + 1]) * COMPARER_SIGN < 0) |
||||
child = child + 1; |
||||
|
||||
// if parent is bigger or equal, than stop |
||||
// if (!MaxHeap) |
||||
// compareResult *= -1; |
||||
if (child > last || |
||||
_comparer.Compare(_nodeList[i], _nodeList[child]) * COMPARER_SIGN >= 0) |
||||
break; |
||||
|
||||
// swap parent and child |
||||
Swap(i, child); |
||||
i = child; |
||||
} |
||||
|
||||
return root; |
||||
} |
||||
|
||||
public int Count { get { return _nodeList.Count; } } |
||||
|
||||
private void Swap(int i, int j) |
||||
{ |
||||
T temp = _nodeList[i]; |
||||
_nodeList[i] = _nodeList[j]; |
||||
_nodeList[j] = temp; |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,22 @@ |
||||
namespace MainNamespace.Structure |
||||
{ |
||||
class HeapClient |
||||
{ |
||||
public static void DoWork(bool maxHeap = true) |
||||
{ |
||||
Heap<int> heap = new Heap<int>(maxHeap); |
||||
heap.Add(11); |
||||
heap.Add(15); |
||||
heap.Add(3); |
||||
heap.Add(5); |
||||
heap.Add(9); |
||||
heap.Add(7); |
||||
heap.Add(1); |
||||
|
||||
while (heap.Count > 0) |
||||
{ |
||||
System.Console.WriteLine(heap.RemoveOne()); |
||||
} |
||||
} |
||||
} |
||||
} |
Loading…
Reference in new issue