Advertisement
Tobiahao

Kolokwium2_Heapsort

Jun 8th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. typedef int int_array_type[10];
  6.  
  7. static inline int get_left_child_index(int index)
  8. {
  9.     return (index << 1) + 1;
  10. }
  11.  
  12. static inline int get_right_child_index(int index)
  13. {
  14.     return (index << 1) + 2;
  15. }
  16.  
  17. void fill_array(int_array_type array)
  18. {
  19.     int i;
  20.     for(i = 0; i < sizeof(int_array_type)/sizeof(array[0]); i++)
  21.         array[i] = rand() % 100;
  22. }
  23.  
  24. void print_array(int_array_type array)
  25. {
  26.     int i;
  27.     for(i = 0; i < sizeof(int_array_type)/sizeof(array[0]); i++)
  28.         printf("%d ", array[i]);
  29.     printf("\n");
  30. }
  31.  
  32. void swap(int *first, int *second)
  33. {
  34.     int tmp = *first;
  35.     *first = *second;
  36.     *second = tmp;
  37. }
  38.  
  39. void heapify(int_array_type array, int index, unsigned int size)
  40. {
  41.     int left = get_left_child_index(index);
  42.     int right = get_right_child_index(index);
  43.     int largest = index;
  44.  
  45.     if(left <= size)
  46.         if(array[left] > array[index])
  47.             largest = left;
  48.     if(right <= size)
  49.         if(array[right] > array[largest])
  50.             largest = right;
  51.     if(largest != index){
  52.         swap(&array[index], &array[largest]);
  53.         heapify(array, largest, size);
  54.     }
  55. }
  56.  
  57. void build_heap(int_array_type array)
  58. {
  59.     int i;
  60.     const int number_of_elements = sizeof(int_array_type)/sizeof(*array);
  61.     for(i = number_of_elements/2; i >= 0; i--)
  62.         heapify(array, i, number_of_elements);
  63. }
  64.  
  65. void heapsort(int_array_type array)
  66. {
  67.     int last_index = sizeof(int_array_type)/sizeof(*array);
  68.     //int last_index = sizeof(int_array_type)/sizeof(*array-1);
  69.  
  70.     int i;
  71.  
  72.     build_heap(array);
  73.     for(i = last_index; i > 0; i--){
  74.         swap(&array[0], &array[i]);
  75.         heapify(array, 0, --last_index);
  76.     }
  77. }
  78.  
  79. int main(void)
  80. {
  81.     srand(time(NULL));
  82.     int_array_type array;
  83.     fill_array(array);
  84.     print_array(array);
  85.     printf("\n");
  86.     heapsort(array);
  87.     print_array(array);
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement