Advertisement
Guest User

12,10...9,11

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