Advertisement
wa12rior

heapsort cpp

May 8th, 2022
635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. void przesiewanie(int q, int p, int *a) {
  6.     int i = q, j = 2*i, x = a[i-1];
  7.  
  8.     while (j < p) {
  9.         if (j < p) {
  10.             if (a[j-1] > a[j]) {
  11.                 j++;
  12.             }
  13.            
  14.             if (x <= a[j-1]) {
  15.                 goto end;
  16.             }
  17.            
  18.             a[i-1] = a[j-1];
  19.             i = j;
  20.             j = 2*i;
  21.         }
  22.     }
  23.     end:
  24.     a[i-1] = x;
  25. }
  26.  
  27. void stogowe(int n, int *a) {
  28.     int q = (n/2) + 1;
  29.     int p = n;
  30.     int x;
  31.    
  32.     while (q > 1) {
  33.         --q;
  34.         przesiewanie(q, p, a);
  35.     }
  36.    
  37.     while (p > 1) {
  38.         x = a[0];
  39.         a[0] = a[p-1];
  40.         a[p-1] = x;
  41.         --p;
  42.         przesiewanie(q, p, a);
  43.     }
  44. }
  45.  
  46. int main() {
  47.     int n = 30;
  48.    
  49.     int tab[n] = {-2, 86, -3, 51, 67, -14, 15, 9, 28, 1, 2, 6, 33, 13, 7, -4, 5, 95, 18, 12, 4, 50, 99, 8, 41, 77, 60, 3, 31};
  50.    
  51.     stogowe(n, tab);
  52.    
  53.     cout<<"\nElementy posortowane:\n";
  54.     for(int i=0; i<n; i++)
  55.             cout<<tab[i]<<" ";
  56.    
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement