Advertisement
shek_shek

Пирамидальная сортировка

Sep 15th, 2014
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stack>
  3. #include<math.h>
  4. #include<iostream>
  5. #include<algorithm>
  6. #include<string.h>
  7. #include<string>
  8. #include<set>
  9. #include<memory.h>
  10. #include<vector>
  11. #include<map>
  12. #include<queue>
  13. #include<iomanip>
  14. #include<ctime>
  15.  
  16. #define forn(i, n) for (int i = 0; i < (n); i++)
  17.  
  18.  
  19. using namespace std;
  20.  
  21. inline int myRand() {
  22.     return (rand() << 16) ^ rand();
  23. }
  24.  
  25. const int N = 1000 * 10;
  26. int h[N];
  27. int n = 0;
  28.  
  29. void heapPush (int x) {
  30.     h[n++] = x;
  31.     int i = n - 1;
  32.     while (i > 0 && h[(i - 1) / 2] < h[i])
  33.         swap(h[i], h[(i - 1) / 2]), i = (i - 1) / 2;
  34. }
  35.  
  36. void heapify(int x) {
  37.     while (2 * x + 1 < n) {
  38.         int j = 2 * x + 1;
  39.         if (j + 1 < n && h[j + 1] > h[j])
  40.             j++;
  41.         if (h[x] >= h[j])
  42.             break;
  43.         swap(h[x], h[j]);
  44.         x = j;
  45.     }
  46. }
  47.  
  48. void heapSort () {
  49.     while (n > 1) {
  50.         heapify(0);
  51.         swap(h[0], h[n - 1]);
  52.         n--;
  53.     }
  54. }
  55.  
  56. int main() {
  57.     srand(time(NULL));
  58.     forn (i, N) {
  59.         int tek = myRand() % N;
  60.         heapPush((tek < 0 ? -tek : tek));
  61.     }
  62.     heapSort();
  63.     forn (i, N) {
  64.         cout << h[i] << " ";
  65.     }
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement