Tassos

heapides !! :D :D :{

Feb 4th, 2015
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. #include <conio.h>
  4.  
  5. using namespace std;
  6.  
  7. void max_heapify(int *a, int i, int n)
  8. /*
  9. a : ο πίνακας.
  10. i : κάποιο στοιχείο από την μέση του πίνακα και κάτω.
  11. n : το πλήθος των στοιχείων όλου του πίνακα.
  12. */
  13. {
  14.  
  15. int aristero_pedi, temp;
  16.  
  17. temp = a[i]; /* παίρνει το εκάστοτε στοιχείο κάτω από την μέση του πίνακα..*/
  18.  
  19. aristero_pedi = 2*i; /* */
  20.  
  21. while (aristero_pedi <= n)
  22.  
  23.     {
  24.  
  25.     if (aristero_pedi < n && a[aristero_pedi+1] > a[aristero_pedi]) /* κατι.. ΚΑΙ ..το δεξί φύλο να είναι πιο μεγαλό από το αριστερό */
  26.         aristero_pedi = aristero_pedi+1; /* */
  27.  
  28.     if (temp > a[aristero_pedi])
  29.         break;
  30.  
  31.     else if (temp <= a[aristero_pedi])
  32.         {
  33.         a[aristero_pedi/2] = aaristero_pedi];
  34.         aristero_pedi = 2*aristero_pedi;
  35.         }
  36.  
  37.     }
  38.  
  39. a[aristero_pedi/2] = temp;
  40.  
  41. return;
  42.  
  43. }
  44.  
  45.  
  46. void heapsort(int *a, int n)
  47.  
  48.     {
  49.  
  50.         int i, temp;
  51.  
  52.         for (i = n; i >= 2; i--)
  53.  
  54.         {
  55.  
  56.             temp = a[i];
  57.  
  58.             a[i] = a[1];
  59.  
  60.             a[1] = temp;
  61.  
  62.             max_heapify(a, 1, i - 1);
  63.  
  64.         }
  65.  
  66.     }
  67.  
  68.  
  69.  
  70.  
  71. void build_maxheap(int *a, int n)
  72. /* n : πλήθος στοιχείων.
  73.   a* : δείκτης στον πίνακα. */
  74.  
  75. {
  76. int i;
  77.  
  78. for(i = n/2; i >= 1; i--)
  79. /* i = με το μέσο του πίνακα & πάρε τον πίνακα από την μέση και κάτω.. */
  80. /* δηλαδή πάμε στους γονέες..*/
  81.     {
  82.     max_heapify(a, i, n);
  83.     }
  84. }
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91. int main()
  92.  
  93. {
  94.  
  95. int n, i, x;
  96.  
  97. cout<<"Πόσα στοιχεία θες να βάλεις στον πίνακα ; \n";
  98.  
  99. cin>>n;
  100.  
  101. int a[20];
  102.  
  103. for (i = 1; i <= n; i++)
  104.  
  105.     {
  106.  
  107.     cout<<"Δώσε το στοχείο  "<< (i) <<endl;
  108.  
  109.     cin>>a[i];
  110.  
  111.     }
  112.  
  113. build_maxheap(a,n);
  114.  
  115. heapsort(a, n);
  116.  
  117. cout<<"sorted output\n";
  118.  
  119. for (i = 1; i <= n; i++)
  120.  
  121. {
  122.  
  123. cout<<a[i]<<endl;
  124.  
  125. }
  126.  
  127. getch();
  128.  
  129.     }
Advertisement
Add Comment
Please, Sign In to add comment