Sort the elements in odd positions in descending order and elements in even positions in ascending order
For Example:
If the input is
For Example:
If the input is
10
1 2 3 4 5 6 7 8 9 10
then the output should be
9 2 7 4 5 6 3 8 1 10Implementation:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a;
int n;
int i,j;
/* get the size of array from the user */
scanf("%d",&n);
/* allocate the memory for the array of size n */
a=(int*)malloc(sizeof(int)*n);
/* get the 'n' values of the array from the user */
for(i=0;i<n;i++)
scanf("%d",(a+i));
/* sort the elements in the odd positions in decreasing order */
for(i=0;i<n;i+=2)
{
for(j=i+2;j<n;j+=2)
{
if(*(a+i) < *(a+j))
{
/* swap the numbers which is not in decreasing order */
/* XOR swap of elements in indices i & j without using third variable */
*(a+i) = *(a+i) ^ *(a+j);
*(a+j) = *(a+i) ^ *(a+j);
*(a+i) = *(a+i) ^ *(a+j);
}
}
}
/* sort the elements in the even positions in ascending order */
for(i=1;i<n;i+=2)
{
for(j=i+2;j<n;j+=2)
{
/* sort the numbers in ascending order if they are not sorted */
if(*(a+i) > *(a+j))
{
/* do an xor swap for the numbers that are not in ascending order */
*(a+i) = *(a+i) ^ *(a+j);
*(a+j) = *(a+i) ^ *(a+j);
*(a+i) = *(a+i) ^ *(a+j);
}
}
}
/* print the elements of the array as:
1. elements in odd positions in descending order
2. elements in even positions in ascending order */
for(i=0;i<n;i++)
printf("%d ",*(a+i));
return 0;
}