Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<typename Typ, unsigned int rozmiar>
- void Tablica<Typ, rozmiar>::heap2(int begin, int end)
- {
- for (int i = begin; i < end; i++)
- {
- int smallerBranch = i; // index odnogi galezi
- int largerBranch = (smallerBranch + begin - 1) / 2; // indeks podstawy (1 wyzej)
- Typ inserted = (*this)[i]; // element wstawiany do kopca
- // przesuwanie w gore dopoki element wyzej jest mniejszy
- while (smallerBranch > begin && (*this)[largerBranch] < inserted)
- {
- // mniejszy element z wyzszej na nizsza galaz
- (*this)[smallerBranch] = (*this)[largerBranch];
- // przejscie indeksami wyzej
- smallerBranch = largerBranch;
- largerBranch = (smallerBranch + begin - 1) / 2;
- }
- // wstawienie elementu na galaz
- // do ktorej dotarla petla
- (*this)[smallerBranch] = inserted;
- }
- }
- template<typename Typ, unsigned int rozmiar>
- void Tablica<Typ, rozmiar>::deheap2(int begin, int end)
- {
- for (int i = end - 1; i > begin; i--)
- {
- // przerzucenie elementu ze szczytu kopca na koniec
- // bo jest najwiekszy
- (*this).swap(begin, i);
- // j - galaz wyzsza, k, m - galaz nizsza
- int j = begin, k = begin + 1, m;
- while (k < i)
- {
- // decyzja: lewa czy prawa odnoga?
- if (k + 1 < i && (*this)[k + 1] > (*this)[k])
- m = k + 1;
- else
- m = k;
- // jesli jest nizej wiekszy element,
- // to zamiana miejscami wyzszego z nizszym.
- if ((*this)[m] > (*this)[j])
- {
- (*this).swap(j, m);
- j = m;
- k = 2 * j - begin + 1;
- }
- else
- break;
- }
- }
- }
- template<typename Typ, unsigned int rozmiar>
- void Tablica<Typ, rozmiar>::heapsort2(int begin, int end)
- {
- (*this).heap2(begin, end);
- (*this).deheap2(begin, end);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement