Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MinIntHeap
- {
- private static int _capacity = 10;
- private int _currentSize = 0;
- private int[] _items = new int[_capacity];
- public int Peek()
- {
- if (_currentSize == 0) throw new Exception();
- return _items[0];
- }
- public int Pop()
- {
- if (_currentSize == 0) throw new Exception();
- int item = _items[0];
- _items[0] = _items[_currentSize - 1];
- _items[_currentSize - 1] = 0;
- _currentSize--;
- HeapifyDown();
- return item;
- }
- public void Insert(int item)
- {
- EnsureExtraCapacity();
- _items[_currentSize] = item;
- _currentSize++;
- HeapifyUp();
- }
- private void HeapifyUp()
- {
- var index = _currentSize - 1;
- while (HasParent(index) && Parent(index) > _items[index])
- {
- Swap(GetParentIndex(index), index);
- index = GetParentIndex(index);
- }
- }
- private void HeapifyDown()
- {
- var index = 0;
- while (HasLeftChild(index))
- {
- var smallerChildIndex = GetLeftChildIndex(index);
- if (HasRightChild(index) && RightChild(index) < LeftChild(index))
- {
- smallerChildIndex = GetRightChildIndex(index);
- }
- if (_items[index] < _items[smallerChildIndex])
- {
- break;
- }
- else
- {
- Swap(smallerChildIndex, index);
- index = smallerChildIndex;
- }
- }
- }
- private void Swap(int indexOne, int indexTwo)
- {
- int temp = _items[indexOne];
- _items[indexOne] = _items[indexTwo];
- _items[indexTwo] = temp;
- }
- private void EnsureExtraCapacity()
- {
- if (_currentSize == _capacity)
- {
- Array.Resize(ref _items, _capacity * 2);
- _capacity *= 2;
- }
- }
- private int GetLeftChildIndex(int parentIndex) => 2 * parentIndex + 1;
- private int GetRightChildIndex(int parentIndex) => 2 * parentIndex + 2;
- private int GetParentIndex(int childIndex) => (childIndex - 1) / 2;
- private bool HasLeftChild(int index) => GetLeftChildIndex(index) < _currentSize;
- private bool HasRightChild(int index) => GetRightChildIndex(index) < _currentSize;
- private bool HasParent(int index) => GetParentIndex(index) >= 0;
- private int LeftChild(int index) => _items[GetLeftChildIndex(index)];
- private int RightChild(int index) => _items[GetRightChildIndex(index)];
- private int Parent(int index) => _items[GetParentIndex(index)];
- }
Add Comment
Please, Sign In to add comment