• Source
    1. #include <iostream>
    2. #include <vector>
    3. //#include <algorithm>
    4.  
    5. int parent(int index)
    6. {
    7. return (index - 1)/2;
    8. }
    9.  
    10. template<typename T>
    11. void max_heapify(std::vector<T>& array, size_t index)
    12. {
    13. size_t largest;
    14. size_t left = (2*index) + 1;
    15. size_t right = left + 1;
    16.  
    17. if(left < array.size() && array[left] > array[index])
    18. largest = left;
    19. else
    20. largest = index;
    21.  
    22. if(right < array.size() && array[right] > array[largest])
    23. largest = right;
    24.  
    25. if(largest != index)
    26. {
    27. std::swap(array[index], array[largest]);
    28. max_heapify(array, largest);
    29. }
    30. }
    31.  
    32. template<typename T>
    33. void build_max_heap(std::vector<T>& array)
    34. {
    35. for(int64_t i = (int64_t(array.size())/2) - 1; i >= 0; i--)
    36. max_heapify(array, i);
    37. }
    38.  
    39. template<typename T>
    40. T heap_maximum(std::vector<T>& array)
    41. {
    42. return array[0];
    43. }
    44.  
    45. template<typename T>
    46. T heap_extract_max(std::vector<T>& array)
    47. {
    48. T max = array[0];
    49. array[0] = array[array.size() - 1];
    50. array.resize(array.size() - 1);
    51. max_heapify(array, 0);
    52. return max;
    53. }
    54.  
    55. template<typename T>
    56. void heap_increase_key(std::vector<T>& array, size_t index, T value)
    57. {
    58. if(value < array[index])
    59. {
    60. std::cerr <<"New value is smaller than the current value\n";
    61. return;
    62. }
    63. else
    64. {
    65. array[index] = value;
    66. while(index > 0 && array[parent(index)] < array[index])
    67. {
    68. std::swap(array[index], array[parent(index)]);
    69. index = parent(index);
    70. }
    71. }
    72. }
    73.  
    74. template<typename T>
    75. void max_heap_insert(std::vector<T>& array, T value)
    76. {
    77. array.resize(array.size() + 1);
    78. array[array.size() - 1] = -1;
    79. heap_increase_key(array, array.size() - 1, value);
    80. }
    81.  
    82. template<typename T>
    83. void print_heap(const std::vector<T>& array)
    84. {
    85. for(size_t i = 0; i < array.size(); i++)
    86. {
    87. std::cout << array[i] << " ";
    88. }
    89. }
    90.  
    91. int main()
    92. {
    93. std::vector<int> v({1, 2, 6, 3, 7});
    94. build_max_heap(v);
    95. std::cout << "Max-Heap: ";
    96. print_heap(v);
    97. std::cout << "\n";
    98. std::cout << "Extract-Maximum: " << heap_extract_max(v) << "\n";
    99. std::cout << "New Heap: ";
    100. print_heap(v);
    101. max_heap_insert(v, 17);
    102. std::cout << "\nNew Heap after inserting 17: ";
    103. print_heap(v);
    104. max_heap_insert(v, 10);
    105. std::cout << "\nNew Heap after inserting 10: ";
    106. print_heap(v);
    107. std::cout << '\n';
    108. }
    109.