Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- void swap (int *a, int *b){
- int temp = *a; *a = *b; *b = temp;
- }
- void fill_array(int* mas, int N, int a, int b){
- int i;
- for (i = 0; i < N; ++i)
- mas[i] = rand()%(b-a+1)+a;
- }
- void shift_down(int* mas, int i, int j){
- int left, right, max_child, temp;
- left = 2*i+1;
- right = left + 1;
- max_child = left;
- while ( max_child < j ) {
- if ( right < j ){
- if ( mas[left] < mas[right] )
- max_child = right;
- if ( mas[i] < mas[max_child] )
- swap (&mas[i], &mas[max_child]);
- } else break;
- i = max_child;
- left = 2*i+1;
- right = left+1;
- max_child = left;
- }
- }
- void heap_sort(int* mas, int N){
- int i;
- for (i = N/2-1; i >= 0; --i)
- shift_down(mas, i, N);
- for (i = N-1; i > 0; --i){
- swap(mas, &mas[i]);
- shift_down(mas, 0, i);
- }
- }
- void print_array(int* mas, int N){
- int i;
- for (i = 0; i < N; ++i)
- printf("%d ", mas[i]);
- printf("\n");
- }
- int main()
- {
- unsigned const int N = 20;
- int a[N];
- fill_array(a, N, -50, 50);
- print_array(a, N);
- heap_sort(a, N);
- print_array(a, N);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement