Advertisement
Guest User

Untitled

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