Advertisement
Lisaveta777

ок2- 12,10...9,11

Nov 12th, 2018
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #define SIZE 12
  3.  
  4. //to sort array, so it goes as follows: 12,10,8,6,4,2,1,3,5,7,9,11
  5. //works fine - with even and neven SIZE, with if/else and with trenary instead,
  6. //with max_index=s/2 as well
  7.  
  8.  
  9. void pr_arr(int s,int *a);
  10. void sort_arr(int s,int *a);
  11. void swap_el(int *a,int ind1,int ind2);
  12.  
  13. int main()
  14. {
  15.     int arr[SIZE]= {1,2,10,3,9,4,8,5,12,6,7,11};
  16.     pr_arr(SIZE,arr);
  17.     sort_arr(SIZE,arr);
  18.     pr_arr(SIZE,arr);
  19.  
  20.     return 0;
  21.  
  22. }
  23.  
  24. void pr_arr(int s,int *a)
  25. {
  26.     int i;
  27.     for(i=0;i<s;i++)
  28.     {
  29.         printf("%d\t",a[i]);
  30.  
  31.     }
  32.     printf("\n\n");
  33. }
  34. void sort_arr(int s,int *a)
  35. {
  36.     int temp,i,j,index_max,up,down =-1;//i-counter,temp is value, everything else
  37.     // is indexes
  38.     up = s, index_max = s/2;
  39.  
  40.  
  41.    for(i=0;i<s;i++)//i -just a cycle counter
  42.    {
  43.        /*if(!(i%2))//i is even, SO we use down as target index
  44.         index_max=++down;
  45.        else//      i is not even,SO we use up as target index
  46.         index_max=--up;*/
  47.  
  48.        (!(i%2))? ++down:  --up;
  49.        //(!(i%2))? index_max=down:--up,index_max=up;
  50.  
  51.        printf("\ni %d\t,down %d\t,up %d\t,index_max %d\n",i,down,up,index_max);
  52.        for(j=down;j<=up;j++)//looking for the max element between down & up
  53.        {
  54.            //printf("j is %d\t",j);
  55.            if(a[j]>a[index_max])
  56.             swap_el(a,j,index_max);
  57.        }
  58.        //swaps a[down] or a[up](depending on i)
  59.        //with a[index_max], OR swaps target element with max element
  60.        (i%2)? swap_el(a,down,index_max):swap_el(a,up,index_max);
  61.        pr_arr(s,a);
  62.    }
  63. }
  64. void swap_el(int *a,int ind1,int ind2)
  65. {
  66.     int temp = a[ind1];
  67.     a[ind1]= a[ind2];
  68.     a[ind2]= temp;
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement