Tuesday, 6 June 2017

Alternate sorting

Alternate sorting: Given an array of integers, rearrange the array in such a way that the first element is first maximum and second element is first minimum.
    Eg.) Input  : {1, 2, 3, 4, 5, 6, 7}
         Output : {7, 1, 6, 2, 5, 3, 4} 
#include<stdio.h>
#include<stdlib.h>
int main()
{
 int i,n,t,j;
 scanf("%d",&n);
 int *a=(int *)malloc(n*sizeof(int)); // creating dynamic array 
  for(i=0;i<n;i++)
  {
   scanf("%d",&a[i]);
  }
  //sorting
  for(i=0;i<n;i++)
  {
   for(j=0;j<n;j++)
   { 
     if(a[i]<a[j])
  { 
   t=a[i];
   a[i]=a[j];
   a[j]=t;
  }
   }
  }
  t=n-1;j=0;
  //printing alternate min max
  for(i=0;i<n;i++)
  {  
   if(i%2!=0){ 
    printf("%d ",a[j] ); ++j;}
    else{
    printf("%d ",a[t] ); --t;}
  }
  
 return 0;
}
OUTPUT : 

1 comment: