Advertisement
Lisaveta777

OK 12,10...9,11

Nov 12th, 2018
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.98 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. //to work on brushing programm, plus making good comments
  8. //code BEFORE it worked fine here: https://pastebin.com/23gEiBWA
  9. //mistake was assigining s-1 to up, instead of s!
  10.  
  11.  
  12. void pr_arr(int s,int *a);
  13. void sort_arr(int s,int *a);
  14. void swap_el(int s,int *a,int ind1,int ind2);
  15.  
  16. int main()
  17. {
  18.     int arr[SIZE]= {1,2,10,3,9,4,8,5,12,6,7,11};
  19.     pr_arr(SIZE,arr);
  20.     sort_arr(SIZE,arr);
  21.     pr_arr(SIZE,arr);
  22.  
  23.     return 0;
  24.  
  25. }
  26.  
  27. void pr_arr(int s,int *a)
  28. {
  29.     int i;
  30.     for(i=0;i<s;i++)
  31.     {
  32.         printf("%d\t",a[i]);
  33.  
  34.     }
  35.     printf("\n\n");
  36. }
  37. void sort_arr(int s,int *a)
  38. {
  39.     int temp,i,j,index_max,up,down =-1;
  40.     up = s;
  41.     index_max = s/2;
  42.  
  43.  
  44.    for(i=0;i<s;i++)//i -just a cycle counter
  45.    {
  46.       //index_max = down;//better to use middle-array index all the time!
  47.        /*if(!(i%2))//i is even, SO we use down as target index
  48.         index_max=++down;
  49.        else//      i is not even,SO we use up as target index
  50.         index_max=--up;*/
  51.  
  52.        (!(i%2))? ++down,index_max=down:--up,index_max=up;//almost good, only order
  53.        //11,9,..1,2..12 (instead of 12,10..2,1..11),or starts with a[11] not a[0]
  54.  
  55.        printf("\ni %d\t,down %d\t,up %d\t,index_max %d\n",i,down,up,index_max);
  56.        for(j=down;j<=up;j++)//looking for the max element between down & up
  57.        {
  58.            //printf("j is %d\t",j);
  59.            if(a[j]>a[index_max])
  60.             swap_el(SIZE,a,j,index_max);
  61.        }
  62.        //swaps a[down] or a[up](depending on i)
  63.        //with a[index_max], OR swaps target element with max element
  64.        (i%2)? swap_el(SIZE,a,down,index_max):swap_el(SIZE,a,up,index_max);
  65.        pr_arr(s,a);
  66.    }
  67. }
  68. void swap_el(int s,int *a,int ind1,int ind2)
  69. {
  70.     int temp = a[ind1];
  71.     a[ind1]= a[ind2];
  72.     a[ind2]= temp;
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement