To sort elements in array based on their position

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:

  1. Get the array elements from the user.
  2. Find the even position and store larger element.
  3. Then find the odd position and store the smaller element.
  4. Repeat step 2 and 3 up to the last element.
  5. At last print the sorted array.

Program:

[code lang=”c”]
#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();
}
[/code]

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.

Leave a Reply

Your email address will not be published. Required fields are marked *