Advertisement
Iamnotagenius

heapsort

Oct 26th, 2021
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdbool.h>
  4. #include <iso646.h>
  5. #include <stdlib.h>
  6. #include <time.h>
  7.  
  8. void swap(int *x, int *y) {
  9.     int tmp = x;
  10.     *x = *y;
  11.     *y = tmp;
  12. }
  13.  
  14. void heapify(int *arr, int size, size_t i) {   
  15.     size_t max;
  16.     while (2 * i + 1 < size) {
  17.         max = arr[i] > arr[i * 2 + 1] ? i : i * 2 + 1;
  18.  
  19.         if (2 * i + 2 < size)
  20.             max = arr[max] > arr[i * 2 + 2] ?
  21.                     max : i * 2 + 2;
  22.  
  23.         swap(arr + i, arr + max);
  24.         if (i == max)
  25.             break;
  26.         i = max;
  27.     }
  28. }
  29.  
  30. void make_heap(int *arr, size_t size) {
  31.     for (size_t i = size / 2; i > 0; --i)
  32.         heapify(arr, size, i);
  33.     heapify(arr, size, 0);
  34. }
  35.  
  36. void heapsort(int *arr, size_t length) {
  37.     make_heap(arr, length);
  38.     while (length > 0) {
  39.         swap(arr, arr + (--length));
  40.         heapify(arr, length, 0);
  41.     }
  42. }
  43.  
  44. const char IN_FILE[] = "heapsort.in";
  45. const char OUT_FILE[] = "heapsort.out";
  46.  
  47. int main() {
  48.     FILE *in = fopen(IN_FILE, "r"),
  49.          *out = fopen(OUT_FILE, "w");
  50.     int n, *arr;
  51.     fscanf(in, "%d", &n);
  52.     arr = malloc(n * sizeof(int));
  53.     for (int i = 0; i < n; ++i)
  54.         fscanf(in, "%d", arr + i);
  55.     heapsort(arr, n);
  56.     for (int i = 0; i < n; ++i)
  57.         fprintf(out, "%d ", arr[i]);
  58.     fprintf(out, "\n");
  59.     return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement