Skip to content

Instantly share code, notes, and snippets.

@mrchnk
Last active July 13, 2021 07:05
Show Gist options
  • Save mrchnk/104a3c18b12f9d4a635e45b6bd986b9a to your computer and use it in GitHub Desktop.
Save mrchnk/104a3c18b12f9d4a635e45b6bd986b9a to your computer and use it in GitHub Desktop.
class BinaryHeap<T>
{
public T[] Heap { get; }
public int Count { get; private set; }
public IComparer<T> Comparer { get; }
public BinaryHeap(int size, IComparer<T> comparer = null)
{
Heap = new T[size];
Count = 0;
Comparer = comparer ?? Comparer<T>.Default;
}
public T Peek()
{
if (Count == 0)
throw new Exception("Empty");
return Heap[0];
}
public void Push(T value)
{
if (Count == Heap.Length)
throw new Exception("Heap overflow");
var i = Count++;
Heap[i] = value;
while (i > 0)
{
var parent = (i + 1) / 2 - 1;
if (IsGreater(Heap[i], Heap[parent]))
break;
Swap(i, parent);
i = parent;
}
}
public T Pop()
{
if (Count == 0)
throw new Exception("Empty");
var v = Heap[0];
var size = --Count;
Swap(0, size);
var i = 0;
while (i < size - 1)
{
var left = i * 2 + 1;
var right = i * 2 + 2;
int child;
if (right < size && IsGreater(Heap[left], Heap[right]))
child = right;
else if (left < size)
child = left;
else
break;
if (IsGreater(Heap[child], Heap[i]))
break;
Swap(i, child);
i = child;
}
return v;
}
private bool IsGreater(T a, T b)
{
return Comparer.Compare(a, b) > 0;
}
private void Swap(int i1, int i2)
{
var v = Heap[i1];
Heap[i1] = Heap[i2];
Heap[i2] = v;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment