Für Vorlesungen, bitte die Webseite verwenden. https://flavigny.de/lecture
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
902B

  1. template<class T>
  2. class Heap {
  3. public:
  4. bool empty ();
  5. void push (T x);
  6. void pop ();
  7. T top ();
  8. private:
  9. std::vector<T> data;
  10. void reheap (int i);
  11. } ;
  12. template<class T>
  13. void Heap<T>::push (T x) {
  14. int i = data.size();
  15. data.push_back(x);
  16. while (i>0 && data[i]>data[(i-1)/2])
  17. {
  18. std::swap(data[i],data[(i-1)/2]);
  19. i = (i-1)/2;
  20. }
  21. }
  22. template <class T>
  23. void Heap<T>::reheap (int i) {
  24. int n = data.size();
  25. while (2*i+1<n)
  26. {
  27. int l = 2*i+1;
  28. int r = l+1;
  29. int k = ((r<n) && (data[r]>data[l])) ? r : l;
  30. if (data[k]<=data[i]) break;
  31. std::swap(data[k], data[i]);
  32. i = k;
  33. }
  34. }
  35. template<class T>
  36. void Heap<T>::pop () {
  37. std::swap(data.front(), data.back());
  38. data.pop_back();
  39. reheap(0);
  40. }
  41. template<class T>
  42. T Heap<T>::top () {
  43. return data[0];
  44. }
  45. template<class T>
  46. inline bool Heap<T>::empty () {
  47. return data.size()==0;
  48. }