Guest User

Untitled

a guest
Jan 17th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. public class MinIntHeap
  2. {
  3. private static int _capacity = 10;
  4. private int _currentSize = 0;
  5. private int[] _items = new int[_capacity];
  6.  
  7. public int Peek()
  8. {
  9. if (_currentSize == 0) throw new Exception();
  10.  
  11. return _items[0];
  12. }
  13.  
  14. public int Pop()
  15. {
  16. if (_currentSize == 0) throw new Exception();
  17.  
  18. int item = _items[0];
  19. _items[0] = _items[_currentSize - 1];
  20. _items[_currentSize - 1] = 0;
  21. _currentSize--;
  22. HeapifyDown();
  23. return item;
  24. }
  25.  
  26. public void Insert(int item)
  27. {
  28. EnsureExtraCapacity();
  29. _items[_currentSize] = item;
  30. _currentSize++;
  31. HeapifyUp();
  32. }
  33.  
  34. private void HeapifyUp()
  35. {
  36. var index = _currentSize - 1;
  37. while (HasParent(index) && Parent(index) > _items[index])
  38. {
  39. Swap(GetParentIndex(index), index);
  40. index = GetParentIndex(index);
  41. }
  42. }
  43.  
  44. private void HeapifyDown()
  45. {
  46. var index = 0;
  47. while (HasLeftChild(index))
  48. {
  49. var smallerChildIndex = GetLeftChildIndex(index);
  50. if (HasRightChild(index) && RightChild(index) < LeftChild(index))
  51. {
  52. smallerChildIndex = GetRightChildIndex(index);
  53. }
  54.  
  55. if (_items[index] < _items[smallerChildIndex])
  56. {
  57. break;
  58. }
  59. else
  60. {
  61. Swap(smallerChildIndex, index);
  62. index = smallerChildIndex;
  63. }
  64. }
  65. }
  66.  
  67. private void Swap(int indexOne, int indexTwo)
  68. {
  69. int temp = _items[indexOne];
  70. _items[indexOne] = _items[indexTwo];
  71. _items[indexTwo] = temp;
  72. }
  73.  
  74. private void EnsureExtraCapacity()
  75. {
  76. if (_currentSize == _capacity)
  77. {
  78. Array.Resize(ref _items, _capacity * 2);
  79. _capacity *= 2;
  80. }
  81. }
  82.  
  83. private int GetLeftChildIndex(int parentIndex) => 2 * parentIndex + 1;
  84. private int GetRightChildIndex(int parentIndex) => 2 * parentIndex + 2;
  85. private int GetParentIndex(int childIndex) => (childIndex - 1) / 2;
  86.  
  87. private bool HasLeftChild(int index) => GetLeftChildIndex(index) < _currentSize;
  88. private bool HasRightChild(int index) => GetRightChildIndex(index) < _currentSize;
  89. private bool HasParent(int index) => GetParentIndex(index) >= 0;
  90.  
  91. private int LeftChild(int index) => _items[GetLeftChildIndex(index)];
  92. private int RightChild(int index) => _items[GetRightChildIndex(index)];
  93. private int Parent(int index) => _items[GetParentIndex(index)];
  94. }
Add Comment
Please, Sign In to add comment