Advertisement
snowywhitee

Untitled

Oct 25th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5.  
  6. void Sink(int A[],int k, int n)
  7. {
  8.     int placed = 0;
  9.     int j = 2*k+1; //el index is k
  10.     while (placed == 0 && j < (n-1))
  11.     {
  12.         if (j < n && A[j] <= A[j+1])
  13.         {
  14.             j = j + 1;
  15.         }
  16.         if (A[k] >= A[j])
  17.         {
  18.             placed = 1;
  19.         }else{
  20.             swap(A[k], A[j]);
  21.         }
  22.         k = j;
  23.         j = 2*k + 1;
  24.     }
  25. }
  26.  
  27. void HeapSort(int A[], int n)
  28. {
  29.     for (int i = (n - 1) / 2; i > -1; i--)
  30.     {
  31.         Sink( A, i, n);
  32.     }
  33.     for (int i = n - 1; i > -1; i--)
  34.     {
  35.         swap(A[0], A[i]);
  36.         Sink(A, 0, i-1);
  37.     }
  38. }
  39.  
  40. int main()
  41. {
  42.     ifstream fin("1.txt");
  43.     ofstream fout("2.txt");
  44.     int n; // number of elmts
  45.     int a[n];
  46.     fin >> n;
  47.     for (int i = 0; i < n; i++)
  48.     {
  49.         fin >> a[i];
  50.     }
  51.     HeapSort(a, n);
  52.     for (int i = 0; i < n; i++)
  53.     {
  54.         cout << a[i] << " ";
  55.     }
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement