SwordPencil

heapsorter.cpp

Dec 23rd, 2016
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include "headlines.h"
  2.  
  3. void HeapSorter::CreateHeap(unsigned k, unsigned n, Stats ** heapStats)
  4. {//Закрытый метод класса "Сортировщик кучей", который осуществляет построение пирамиды.
  5.     long newElement = tempArray[k];
  6.     unsigned child = 0;
  7.     while(k <= n / 2)
  8.     {
  9.         child = 2 * k;
  10.         (*heapStats)->compareCount++;
  11.         if (child < n && this->tempArray[child] < this->tempArray[child + 1])
  12.             child++;
  13.         (*heapStats)->compareCount++;
  14.         if (newElement >= this->tempArray[child]) break;
  15.             this->tempArray[k] = this->tempArray[child];
  16.         k = child;
  17.     }
  18.     this->tempArray[k] = newElement;
  19. }
  20.  
  21. Stats HeapSorter::SortArray(long * arrayToSort, unsigned length)
  22. {//Сортировка пирамидальная.
  23.     Stats * heapStats = new Stats("Куча");
  24.     this->SetTempArray(arrayToSort, length); //Создаем временный массив.
  25.     long temp = 0;
  26.     for(int i = length / 2 - 1; i >= 0; i--)
  27.         CreateHeap(i, length - 1, &heapStats); //Строим пирамиду.
  28.     for(int i = length - 1; i > 0; i--)
  29.     {
  30.         swap(this->tempArray[i], this->tempArray[0]);
  31.         heapStats->swapCount++;
  32.         CreateHeap(0, i - 1, &heapStats); //Восстанавливаем пирамидальность
  33.     }
  34.     ShowArray(this->tempArray, length);
  35.     return *heapStats;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment