Advertisement
Guest User

zyciejestnowela

a guest
Jun 24th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. int left(int i)
  5. {
  6.     return 2*i+1;
  7. }
  8.  
  9. int right(int i)
  10. {
  11.     return 2*i+2;
  12. }
  13.  
  14. int parent(int i)
  15. {
  16.     return (i-1)/2;
  17. }
  18.  
  19. void kopiec_przywroc(int *A,int i,int length)
  20. {
  21.     int max,tmp;
  22.     int l=left(i);
  23.     int r=right(i);
  24.     if(l<length && A[l]>A[i])
  25.     {
  26.     max=l;
  27.     }
  28.     else{
  29.         max=i;
  30.     }
  31.     if(r<length &&A[r]>A[max])
  32.     {
  33.         max=r;
  34.     }
  35.     if(max!=i){
  36.         tmp=A[i];
  37.         A[i]=A[max];
  38.         A[max]=tmp;
  39.         kopiec_przywroc(A,max,length);
  40.     }
  41. }
  42.  
  43. void kopiec_buduj(int *A,int length)
  44. {
  45.     int i;
  46.     for(i=length/2;i>=0;i--)
  47.     {
  48.     kopiec_przywroc(A,i,length);
  49.     }
  50. }
  51.  
  52. int kopiec_usun_max(int *A,int *heap_size)
  53. {
  54.     int max;
  55.     if(*heap_size<1)
  56.     {
  57.         return -1;
  58.     }
  59.     max=A[0];
  60.     A[0]=A[*heap_size-1];
  61.     (*heap_size)--;
  62.     kopiec_przywroc(A,0,*heap_size);
  63.     return max;
  64.  
  65. }
  66.  
  67. int main()
  68. {
  69.     int rozmiar,i;
  70.     int *A=NULL;
  71.     printf("Podaj rozmiar tablicy: ");
  72.     fflush(stdin);
  73.     scanf("%d",&rozmiar);
  74.     A=(int *) malloc(rozmiar*sizeof(int));
  75.  
  76.     for(i=0;i<rozmiar;i++)
  77.     {
  78.         printf("\nTablica[%i]=",i);
  79.         fflush(stdin);
  80.         scanf("%d",&A[i]);
  81.     }
  82.  
  83.     kopiec_buduj(A,rozmiar);
  84.  
  85.     for(i=0;i<rozmiar;i++)
  86.     {
  87.         printf("%d ",A[i]);
  88.     }
  89.     printf("\n");
  90.  
  91.     getch();
  92.  
  93.  
  94. return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement