irapilguy

Heap

Nov 11th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.48 KB | None | 0 0
  1. #define N 1000
  2. int mas[N];
  3. void swapp(int i, int j) {
  4.     int x = mas[i];
  5.     mas[i] = mas[j];
  6.     mas[j] = x;
  7. }
  8. void siftUp(int i) {
  9.     if (i == 1) return;
  10.     int p = i / 2;
  11.     if (mas[p] < mas[i]) {
  12.         swapp(p, i);
  13.         siftUp(p);
  14.     }
  15. }
  16. void siftDown(int i,int n) {
  17.     int l = 2 * i;
  18.     int r = 2 * i + 1;
  19.     int max = i;
  20.     if (max > n + 1) return;
  21.     if (l <= n && mas[max] < mas[l]) max = l;
  22.     if (r <= n && mas[max] < mas[r]) max = r;
  23.     if (max != i) {
  24.         swapp(max, i);
  25.         siftDown(max, n);
  26.     }
  27. }
Add Comment
Please, Sign In to add comment