Advertisement
dmkozyrev

heap_sort

May 31st, 2015
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void swap (int *a, int *b){
  4.   int temp = *a; *a = *b; *b = temp;
  5. }
  6.  
  7. void fill_array(int* mas, int N, int a, int b){
  8.     int i;
  9.     for (i = 0; i < N; ++i)
  10.         mas[i] = rand()%(b-a+1)+a;
  11. }
  12.  
  13. void shift_down(int* mas, int i, int j){
  14.     int left, right, max_child, temp;
  15.     left = 2*i+1;
  16.     right = left + 1;
  17.     max_child = left;
  18.     while ( max_child < j ) {
  19.         if ( right < j ){
  20.             if ( mas[left] < mas[right] )
  21.                 max_child = right;
  22.             if ( mas[i] < mas[max_child] )
  23.                 swap (&mas[i], &mas[max_child]);
  24.         } else break;
  25.         i = max_child;
  26.         left = 2*i+1;
  27.         right = left+1;
  28.         max_child = left;
  29.     }
  30. }
  31.  
  32. void heap_sort(int* mas, int N){
  33.     int i;
  34.     for (i = N/2-1; i >= 0; --i)
  35.         shift_down(mas, i, N);
  36.  
  37.     for (i = N-1; i > 0; --i){
  38.         swap(mas, &mas[i]);
  39.         shift_down(mas, 0, i);
  40.     }
  41. }
  42.  
  43. void print_array(int* mas, int N){
  44.     int i;
  45.     for (i = 0; i < N; ++i)
  46.         printf("%d ", mas[i]);
  47.     printf("\n");
  48. }
  49.  
  50. int main()
  51. {
  52.     unsigned const int N = 20;
  53.     int a[N];
  54.     fill_array(a, N, -50, 50);
  55.     print_array(a, N);
  56.     heap_sort(a, N);
  57.     print_array(a, N);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement