Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. void swap(int* a, int* b);
  7. void getElements(int* array, int size, int* flagOfWrongInput);
  8. void buildHeap(int* array, int size);
  9. void heapSort(int* array, int size);
  10.  
  11. void swap(int* a, int* b) {
  12.     int temp = *a;
  13.     *a = *b;
  14.     *b = temp;
  15. }
  16.  
  17. void getElements(int* array, int size, int* flagOfWrongInput) {
  18.     for (int i = 0; i < size; i++) {
  19.         if (scanf("%d", array + i) == 0) {
  20.             printf("bad input");
  21.             (*flagOfWrongInput)++;
  22.             return;
  23.         }
  24.         buildHeap(array, i + 1);
  25.     }
  26. }
  27.  
  28. void buildHeap(int* array, int size) {
  29.     int currentIndex = size - 1;
  30.     while (currentIndex != 0) {
  31.         if (array[currentIndex] < array[(currentIndex - 1) / 2]) {
  32.             swap(array + currentIndex, array + (currentIndex - 1) / 2);
  33.             currentIndex = (currentIndex - 1) / 2;
  34.         }
  35.         else break;
  36.     }
  37. }
  38.  
  39. void heapSort(int* array, int size) {
  40.     while (size > 0) {
  41.         swap(array, array + size - 1);
  42.         printf("%d ", array[size - 1]);
  43.         size--;
  44.         int currentIndex = 0;
  45.         while (1) {
  46.             if (2 * currentIndex + 2 < size && array[2 * currentIndex + 2] < array[2 * currentIndex + 1]) {
  47.                 swap(array + currentIndex, array + 2 * currentIndex + 2);
  48.                 currentIndex = 2 * currentIndex + 2;
  49.             }
  50.             else if (2 * currentIndex + 1 < size && array[currentIndex] > array[2 * currentIndex + 1]) {
  51.                 swap(array + currentIndex, array + 2 * currentIndex + 1);
  52.                 currentIndex = 2 * currentIndex + 1;
  53.             }
  54.             else break;
  55.         }
  56.     }
  57. }
  58.  
  59. int main() {
  60.     int n;
  61.     if (scanf("%d", &n) == 0) {
  62.         printf("bad input");
  63.     }
  64.     int flagOfWrongInput = 0;
  65.     const int ZERO = 0;
  66.     int* array = (int*)calloc((size_t)n, sizeof(int));
  67.     getElements(array, n, &flagOfWrongInput);
  68.     if (flagOfWrongInput == ZERO) {
  69.         heapSort(array, n);
  70.     }
  71.     free(array);
  72.     system("pause");
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement