To sort elements in array based on their position
Question:
Write a program to sort elements in the array by even position in descending order and od position ascending order.
Logic:
- Get the array elements from the user.
- Then make even position are in ascending and odd position in descending order.
- And then print the sorted array.
Algorithm:
- Get the array elements from the user.
- Find the even position and store larger element.
- Then find the odd position and store the smaller element.
- Repeat step 2 and 3 up to the last element.
- At last print the sorted array.
Program:
#include<stdio.h> void main() { int i,a[20],n,temp,j; clrscr(); printf("enter the size of array:"); scanf("%d",&n); printf("enter the elements:"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(i%2==0)//checks for even position { if(a[i]<a[j])//checks for larger number { temp=a[i]; a[i]=a[j]; a[j]=temp; } } else//odd position { if(a[i]>a[j])//checks for smaller number { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } } printf("numbers after sorting:"); for(i=0;i<n;i++)//prints the sorted elements { printf("%d ",a[i]); } getch(); }