Advertisement
Guest User

7-2

a guest
Apr 21st, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void down(int *mass, int root, int bottom) {
  5.     int maxChild;
  6.     int done = 0;
  7.     while ((root * 2 <= bottom) && (!done))
  8.     {
  9.         if (root * 2 == bottom)
  10.             maxChild = root * 2;
  11.         else if (mass[root * 2] > mass[root * 2 + 1])
  12.             maxChild = root * 2;
  13.         else
  14.             maxChild = root * 2 + 1;
  15.         if (mass[root] < mass[maxChild])
  16.         {
  17.             int temp = mass[root];
  18.             mass[root] = mass[maxChild];
  19.             mass[maxChild] = temp;
  20.             root = maxChild;
  21.         }
  22.         else
  23.             done = 1;
  24.     }
  25. }
  26.  
  27. int sorting_function(int *mass, int arr_len) {
  28.     for (int i = (arr_len / 2) - 1; i >= 0; i--)
  29.         down(mass, i, arr_len - 1);
  30.     for (int i = arr_len - 1; i >= 1; i--)
  31.     {
  32.         int temp = mass[0];
  33.         mass[0] = mass[i];
  34.         mass[i] = temp;
  35.         down(mass, 0, i - 1);
  36.     }
  37.     return 0;
  38. }
  39.  
  40. int main() {
  41.     int *mass;
  42.     int n;
  43.     scanf("%d", &n);
  44.     mass = (int*)malloc(n * sizeof(int));
  45.     for (int i = 0; i < n; i++){
  46.         scanf("%d", &mass[i]);
  47.     }
  48.  
  49.     sorting_function(mass, n);
  50.  
  51.     for (int i = 0; i < n; i++) {
  52.         if (i == n - 1){
  53.             printf("%d\n", mass[i]);
  54.             break;
  55.         }
  56.         printf("%d ", mass[i]);
  57.     }
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement