Friday, June 26, 2020

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

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 

PROGRAM:

 
#include<stdio.h> 
int main() 
{ 
    int n,i,j,e=0,o=0,t1,t; 
    scanf("%d",&n); 
    int a[10],b[10],c[10]; 
    for(i=0;i<n;i++) 
    { 
        scanf("%d",&a[i]); 
         
        if(i%2==0) 
        { 
            b[e]=a[i]; 
            e++; 
        }  
        else 
        { 
            c[o]=a[i]; 
            o++; 
         }  
    } 
    
    for(i=0;i<o;i++) 
    { 
     for(j=0;j<o;j++) 
         { 
          if(c[i]<c[j]) 
           { 
               t=c[i]; 
               c[i]=c[j];       
               c[j]=t; 
            } 
          }     
     } 
     for(i=0;i<e;i++) 
     { 
      for(j=0;j<e;j++) 
       { 
         if(b[i]>b[j]) 
           { 
               t1=b[i]; 
               b[i]=b[j]; 
               b[j]=t1; 
           } 
        } 
      }    
    e=0;o=0; 
    for(i=0;i<n;i++) 
    { 
        if(i%2==0) 
        {     
           printf("%d ",b[e]); 
           e++; 
        } 
       else 
        { 
            printf("%d ",c[o]); 
            o++; 
        } 
    } 
} 
 
OUTPUT:

7                                                                                                                     
13 2 4 15 12 10 5                                                                                                     
13 2 12 10 5 15 4

No comments:

Post a Comment