Max_Leb

C1

Jun 16th, 2022
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4.  
  5. void swap(int *a, int *b) {
  6.     int tmp = *a;
  7.     *a = *b;
  8.     *b = tmp;
  9. }
  10.  
  11.  
  12. void siftUp(int *heap, int i) {
  13.     while (i > 0) {
  14.         swap(&heap[i], &heap[(i - 1) / 2]);
  15.         i = (i - 1) / 2;
  16.     }
  17. }
  18.  
  19.  
  20. int main() {
  21.     std::ifstream fin("heapsort.in");
  22.     std::ofstream fout("heapsort.out");
  23.  
  24.     int n;
  25.     fin >> n;
  26.     int heap[n];
  27.     int size = 0;
  28.  
  29.     int index = 0;
  30.     for (int i = 1; i <= n; ++i) {
  31.         heap[index++] = i;
  32.         size++;
  33.     }
  34.  
  35.     for (int i = 1; i < n; ++i) {
  36.         int tmp = i;
  37.         swap(&heap[0], &heap[i]);
  38.         if (i == n - 1)
  39.             break;
  40.         siftUp(heap, tmp);
  41.     }
  42.  
  43.     for (int i = 0; i < size; ++i) {
  44.         fout << heap[i] << " ";
  45.     }
  46.  
  47.     fin.close();
  48.     fout.close();
  49.  
  50.  
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment