Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. include "heap.h"
  2.  
  3. Heap::Heap(vector<int>& vec)
  4. {
  5. h = vec;
  6. for(int i = (int)h.size()/2; i >=0; i--)
  7. {
  8. correct(i);
  9. }
  10.  
  11. }
  12.  
  13. void Heap::add(int value)
  14. {
  15. h.push_back(value);
  16. int current_index = h.size() - 1;
  17. int parent = (current_index - 1)/2;
  18. while(h[current_index] > h[parent])
  19. {
  20. swap(h[current_index], h[parent]);
  21. current_index = parent;
  22. parent = (parent - 1)/2;
  23. }
  24. }
  25.  
  26. void Heap::pop()
  27. {
  28.  
  29. std::swap(h[0], h[h.size()-1]);
  30. h.erase(h.begin() + h.size()-1);
  31. correct(0);
  32.  
  33. }
  34.  
  35. void Heap::print()
  36. {
  37. for(int i = 0; i < h.size(); i++)
  38. {
  39. cout << h[i] << " ";
  40. }
  41. cout << endl;
  42. }
  43.  
  44. void Heap::correct(int index)
  45. {
  46. unsigned left_index,right_index,biggest_child;
  47. while(1)
  48. {
  49. left_index=2*index+1;
  50. right_index=2*index+2;
  51. biggest_child=index;
  52. if(left_index<h.size()&&h[left_index]>h[biggest_child])
  53. {
  54. biggest_child=left_index;
  55. }
  56. if(right_index<h.size()&&h[right_index]>h[biggest_child])
  57. {
  58. biggest_child=right_index;
  59. }
  60. if(biggest_child==index)
  61. break;
  62. swap(h[index],h[biggest_child]);
  63. index=biggest_child;
  64. }
  65. }
  66.  
  67. void Heap::increase(int index, int change)
  68. {
  69. if(index >= h.size() || index < 0 || change < 0)
  70. {
  71. throw exception();
  72. }
  73. h[index] += change;
  74. int current_index = index;
  75. int parent = (current_index - 1)/2;
  76. while(h[current_index] > h[parent])
  77. {
  78. swap(h[current_index], h[parent]);
  79. current_index = parent;
  80. parent = (parent - 1)/2;
  81. }
  82. }
  83.  
  84. void Heap::decrement(int index, int change)
  85. {
  86. if(index >= h.size() || index < 0 || change < 0)
  87. {
  88. throw exception();
  89. }
  90. h[index] -= change;
  91. correct(index);
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement