Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdbool.h>
- #include <iso646.h>
- #include <stdlib.h>
- #include <time.h>
- void swap(int *x, int *y) {
- int tmp = x;
- *x = *y;
- *y = tmp;
- }
- void heapify(int *arr, int size, size_t i) {
- size_t max;
- while (2 * i + 1 < size) {
- max = arr[i] > arr[i * 2 + 1] ? i : i * 2 + 1;
- if (2 * i + 2 < size)
- max = arr[max] > arr[i * 2 + 2] ?
- max : i * 2 + 2;
- swap(arr + i, arr + max);
- if (i == max)
- break;
- i = max;
- }
- }
- void make_heap(int *arr, size_t size) {
- for (size_t i = size / 2; i > 0; --i)
- heapify(arr, size, i);
- heapify(arr, size, 0);
- }
- void heapsort(int *arr, size_t length) {
- make_heap(arr, length);
- while (length > 0) {
- swap(arr, arr + (--length));
- heapify(arr, length, 0);
- }
- }
- const char IN_FILE[] = "heapsort.in";
- const char OUT_FILE[] = "heapsort.out";
- int main() {
- FILE *in = fopen(IN_FILE, "r"),
- *out = fopen(OUT_FILE, "w");
- int n, *arr;
- fscanf(in, "%d", &n);
- arr = malloc(n * sizeof(int));
- for (int i = 0; i < n; ++i)
- fscanf(in, "%d", arr + i);
- heapsort(arr, n);
- for (int i = 0; i < n; ++i)
- fprintf(out, "%d ", arr[i]);
- fprintf(out, "\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement