Advertisement
Guest User

Untitled

a guest
May 27th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. using namespace std;
  5.  
  6. void heap_help(int*,int, int);
  7.  
  8. void heap_sort(int *a, int n)
  9. { for(int i=n/2-1; i >= 0; i--) heap_help(a, i, n);
  10. for(int i=n-1; i>0; i--)
  11. { swap(a[0], a[i]);
  12. heap_help(a, 0, i);
  13. }
  14. }
  15.  
  16. void heap_help(int* a, int hole, int n) {
  17. int val =a[hole];
  18. int i = 2*hole+1;
  19. while (i < n) {
  20. if ( i < n-1 && a[i] < a[i+1]) i++;
  21. if(val<a[i]) {
  22. a[hole] = a[i];
  23. hole = i;
  24. i = 2 * i + 1;}
  25. else i = n;
  26. }
  27. a[hole] = val;
  28. }
  29.  
  30. int main()
  31. {
  32. int n;
  33. cin>>n;
  34. int* a = new int[n];
  35.  
  36. for(int i=0; i<n; i++)
  37. a[i] = rand()%100;
  38. for(int i=0; i<n; i++)
  39. cout<<a[i]<<' '; cout<<endl;
  40.  
  41. heap_sort(a,n);
  42.  
  43. for(int i=0; i<n; i++)
  44. cout<<a[i]<<' ';
  45.  
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement