Tuesday 6 June 2017

Write a program to sort the elements in odd positions in descending order and elements in ascending order

Eg 1: Input: 13,2 4,15,12,10,5
        Output: 13,2,12,10,5,15,4
Eg 2: Input: 1,2,3,4,5,6,7,8,9
        Output: 9,2,7,4,5,6,3,8,1 
#include<stdio.h>
int main()
{
    int n,i,k=0,j,t=0,t1;
    scanf("%d",&n);
    int a[n],b[n/2],c[n/2];
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
        if(i%2==0)
        {b[k]=a[i];++k;}//printf("%d ",a[i]);
        else
        {c[t]=a[i];++t;} 
    }
    for(i=0;i<t;i++)
     for(j=0;j<t;j++)
          if(c[i]<c[j])
           {
               t1=c[i];
               c[i]=c[j];
               c[j]=t1;
     for(i=0;i<k;i++)
      for(j=0;j<k;j++)
         if(b[i]>b[j])
           {
               t=b[i];
               b[i]=b[j];
               b[j]=t;
           }   
   k=0;t=0;
    for(i=0;i<n;i++)
    {
        if(i%2==0)
           printf("%d ",b[k]);++k;
       else
            printf("%d ",c[t++]);
    }
    return 0;
}

1 comment:

  1. class Program
    {
    public static void swap(ref int a, ref int b)
    {
    int temp;
    temp = a;
    a = b;
    b = temp;
    }
    static void Main(string[] args)
    {
    int[] A = {13, 2, 4, 15, 12, 10, 5};
    int n = A.Length;



    for(int i = 0; i < n && i+2 <= n-1 ; i++)
    {
    for(int j = 0; j < n && j + 2 <= n - 1; j++)
    {
    if (j % 2 == 0) // index (0 2) position (1 3) odd position
    {
    if (A[j] < A[j + 2])
    {
    swap(ref A[j], ref A[j + 2]);
    }

    }
    else //index (1 3) position (2 4) even position
    {
    if (A[j] > A[j + 2])
    {
    swap(ref A[j], ref A[j + 2]);
    }
    }
    }

    }

    //print array
    for(int i =0; i < n;i++)
    {
    Console.Write(A[i] +"\t");
    }

    Console.ReadKey();
    }
    }

    ReplyDelete