Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. template<typename Typ, unsigned int rozmiar>
  2. void Tablica<Typ, rozmiar>::heap2(int begin, int end)
  3. {
  4.     for (int i = begin; i < end; i++)
  5.     {
  6.         int smallerBranch = i;              // index odnogi galezi
  7.         int largerBranch = (smallerBranch + begin - 1) / 2; // indeks podstawy (1 wyzej)
  8.         Typ inserted = (*this)[i];    // element wstawiany do kopca
  9.  
  10.         // przesuwanie w gore dopoki element wyzej jest mniejszy
  11.         while (smallerBranch > begin && (*this)[largerBranch] < inserted)
  12.         {
  13.             // mniejszy element z wyzszej na nizsza galaz
  14.             (*this)[smallerBranch] = (*this)[largerBranch];
  15.  
  16.             // przejscie indeksami wyzej
  17.             smallerBranch = largerBranch;
  18.             largerBranch = (smallerBranch + begin - 1) / 2;
  19.         }
  20.  
  21.         // wstawienie elementu na galaz
  22.         // do ktorej dotarla petla
  23.         (*this)[smallerBranch] = inserted;
  24.     }
  25. }
  26.  
  27. template<typename Typ, unsigned int rozmiar>
  28. void Tablica<Typ, rozmiar>::deheap2(int begin, int end)
  29. {
  30.     for (int i = end - 1; i > begin; i--)
  31.     {
  32.         // przerzucenie elementu ze szczytu kopca na koniec
  33.         // bo jest najwiekszy
  34.         (*this).swap(begin, i);
  35.  
  36.         // j - galaz wyzsza, k, m - galaz nizsza
  37.         int j = begin, k = begin + 1, m;
  38.  
  39.         while (k < i)
  40.         {
  41.             // decyzja: lewa czy prawa odnoga?
  42.             if (k + 1 < i && (*this)[k + 1] > (*this)[k])
  43.                 m = k + 1;
  44.             else
  45.                 m = k;
  46.  
  47.             // jesli jest nizej wiekszy element,
  48.             // to zamiana miejscami wyzszego z nizszym.
  49.             if ((*this)[m] > (*this)[j])
  50.             {
  51.                 (*this).swap(j, m);
  52.                 j = m;
  53.                 k = 2 * j - begin + 1;
  54.             }
  55.             else
  56.                 break;
  57.         }
  58.     }
  59. }
  60.  
  61. template<typename Typ, unsigned int rozmiar>
  62. void Tablica<Typ, rozmiar>::heapsort2(int begin, int end)
  63. {
  64.     (*this).heap2(begin, end);
  65.     (*this).deheap2(begin, end);
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement