Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #define SIZE 12
- //suppose to sort array, so it goes as follows: 12,10,8,6,4,2,1,3,5,7,9,11
- //instead it goes like that: 11,9,7,5,3,1,2,4,6,8,10,12
- //can't figure out where i'm mistaken?
- // печать массива длиной s и указателем на него a
- void pr_arr(int s, int *a);
- // сортировка массива длиной s и указателем на него a
- void sort_arr(int s, int *a);
- int main()
- {
- int arr[SIZE] = {1,2,10,3,9,4,8,5,12,6,7,11};
- pr_arr(SIZE, arr); // печатаем массив
- sort_arr(SIZE, arr); // сортируем массив
- pr_arr(SIZE, arr); // распечатаем полученный массив
- return 0;
- }
- // печать массива длиной s и указателем на него a
- void pr_arr(int s, int *a)
- {
- int i;
- for(i=0; i<s; i++) printf("%d ", a[i]);
- printf("\n\n");
- }
- // обмен элементов в массиве по указателю a (ind - индексы для обмена)
- inline void swap_el(int *a, int ind1, int ind2)
- {
- int temp = a[ind1];
- a[ind1] = a[ind2];
- a[ind2] = temp;
- }
- // сортировка массива длиной s и указателем на него a
- void sort_arr(int s, int *a)
- {
- int temp, i, j, index_max, up, down=-1;
- //down - target index for even i cycles,it
- //covers first 6 elements of an array a[0] to a[5],up - for uneven cycles
- //i/down 0/0, 2/1, 4/2, 6/3, 8/4, 10/5
- //i/up 1/11,3/10, 5/9, 7/8, 9/7, 11/6
- up = s-1;
- i=0;
- for(i=0; i<s; i++) //i -just a cycle counter
- {
- if( !(i%2) ) //i is even, SO target index now is down
- index_max = ++down;
- else //i is not even,SO target index now is up
- index_max = --up;
- //(!(i%2))? ++down,index_max=down:--up,index_max=up;//almost good, only order
- //11,9,..1,2..12 (instead of 12,10..2,1..11),or starts with a[11] not a[0]
- printf("\ni %d\t,down %d\t,up %d\t,index_max %d\n", i, down, up, index_max);
- for(j=down; j<=up; j++)//looking for the max element between down & up
- {
- //printf("j is %d\t",j);
- if( a[j] > a[index_max] )
- swap_el(a, j, index_max); // обмен элементов
- }
- //swaps a[down] or a[up](depending on i)
- //with a[index_max], OR swaps target element with max element
- (i%2) ? swap_el(a, down, index_max)
- : swap_el(a, up, index_max);
- pr_arr(s,a); // печать массива
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement