Advertisement
Guest User

Untitled

a guest
Jan 16th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. void addToMaxHeap(int* heap, int& heapSize, int arraySize, int value);
  4. int parent(int childIndex);
  5. int left(int parentIndex);
  6. int right(int parentIndex);
  7. void swap(int& a, int& b);
  8. void displayHeap(int* heap, int heapSize);
  9. void sort(int* heap, int& heapSize);
  10.  
  11. int main()
  12. {
  13.     const auto arraySize = 10;
  14.     const auto values = new int[arraySize] { 1, 3, 56, 6, 7, 12, 7, 65, 22, 18 };
  15.     const auto heap = new int[arraySize];
  16.     auto heapSize = 0;
  17.  
  18.     for (auto i = 0; i < arraySize; i++)
  19.         addToMaxHeap(heap, heapSize, arraySize, values[i]);
  20.  
  21.     displayHeap(heap, heapSize);
  22.     std::cout << std::endl;
  23.  
  24.     sort(heap, heapSize);
  25.     displayHeap(heap, arraySize);
  26.  
  27.     getchar();
  28.     return EXIT_SUCCESS;
  29. }
  30.  
  31. void sort(int* heap, int& heapSize)
  32. {
  33.     while (heapSize > 0)
  34.     {
  35.         swap(heap[heapSize - 1], heap[0]);
  36.         heapSize--;
  37.  
  38.         auto current = 0;
  39.         auto biggest = heap[left(current)] > heap[right(current)] ? left(current) : right(current);
  40.  
  41.         while (heap[biggest] > heap[current] && biggest < heapSize)
  42.         {
  43.             swap(heap[biggest], heap[current]);
  44.             current = biggest;
  45.             biggest = heap[left(current)] > heap[right(current)] ? left(current) : right(current);
  46.         }
  47.     }
  48. }
  49.  
  50. void addToMaxHeap(int* heap, int& heapSize, const int arraySize, const int value)
  51. {
  52.     if (heapSize >= arraySize)
  53.         return;
  54.  
  55.     heap[heapSize] = value;
  56.     auto current = heapSize;
  57.     heapSize++;
  58.  
  59.     while (current > 0 && heap[current] > heap[parent(current)])
  60.     {
  61.         swap(heap[current], heap[parent(current)]);
  62.         current = parent(current);
  63.     }
  64. }
  65.  
  66. int parent(const int childIndex)
  67. {
  68.     return childIndex % 2 ? (childIndex - 1) / 2 : childIndex / 2;
  69. }
  70.  
  71. int left(const int parentIndex)
  72. {
  73.     return parentIndex * 2 + 1;
  74. }
  75.  
  76. int right(const int parentIndex)
  77. {
  78.     return parentIndex * 2 + 2;
  79. }
  80.  
  81. void swap(int& a, int& b)
  82. {
  83.     const auto c = a;
  84.     a = b;
  85.     b = c;
  86. }
  87.  
  88. void displayHeap(int* heap, const int heapSize)
  89. {
  90.     for (auto i = 0; i < heapSize; i++)
  91.         std::cout << heap[i] << " ";
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement