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;
}

6 comments:

  1. compilation error at 37th line else without previous if

    ReplyDelete
    Replies
    1. You just put bracekets:
      if(i%2==0){
      printf("%d ",b[k]);++k;}
      else{
      printf("%d ",c[t++]);}
      It will work..

      Delete
  2. JAVA :

    public class OddEvenArr {
    public static void main(String[] args) {
    int[] a= {13,2,4,15,12,10,5};
    for (int i = 0; i < a.length; i+=2) {
    for (int j = i+2; j < a.length; j+=2) {
    int temp;
    if (a[i]a[j]) {
    temp=a[i];
    a[i]=a[j];
    a[j]=temp;
    }
    }
    }
    System.out.println(Arrays.toString(a));
    }
    }

    ReplyDelete