13 June 2018

alternate sorting 2


to sort the elements in odd positions in descending order and elements in even positions ascending order

i/p:
    6,5,4,9,8,7,1
o/p:
    1,9,4,7,6,5,8 

public class NewClass15 {
     void print(int ar[])
     {
         for(int i=0;i<ar.length;i++)
             System.out.print(ar[i]+" ");
     }
    void alternatesort(int ar[],int i)
    {
       
            if(i%2==0){
            for(int j=i+2;j<ar.length;j+=2)
            {
                if(ar[i]>ar[j])
                {
                    ar[i]=ar[i]+ar[j];
                    ar[j]=ar[i]-ar[j];
                    ar[i]=ar[i]-ar[j];
                }
            }        
                      }
            else {
                for(int j=i+2;j<ar.length;j+=2)
                  {
                   if(ar[i]<ar[j])
                    {
                    ar[i]=ar[i]+ar[j];
                    ar[j]=ar[i]-ar[j];
                    ar[i]=ar[i]-ar[j];
                    }
                  } 
               }
          if(i<ar.length-1)
              alternatesort(ar,++i);
    }
   
public static void main(String args[])
    {
        NewClass15 ob=new NewClass15();
        int ar[]={5,4,3,9,8,7,2};
        ob.alternatesort(ar,0);
        ob.print(ar);
    }
}

No comments:

Post a Comment