Monday, May 6, 2013

Arranging values in an array in zig zag manner



Few values are to be taken from user and the values will be arranged in ascending order but in a zig zag manner. The smallest value will be placed at the extreme left side (at zero index location) and the next value will be at the extreme right location (last index location). Similarly the third value in the ‘1’ index location and 4rth value at the (size-2) location of the array and so on.

Here is the BlueJ program


import java.io.*;
class Ab1
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 int c=0,minvalue,minindex,k,arr[],i,j,n,t,x=0,y;
 public void take() throws Exception
 {
 System.out.println("How many elements:");
 n=Integer.parseInt(br.readLine());
 arr=new int[n];
 for (i=0;i< n;i++)
 {
 System.out.println("How many elements:");
 arr[i]=Integer.parseInt(br.readLine());
 }
 System.out.println("\nOriginal elements in the array=");
      for(i=0;i< n;i++)
    System.out.print("  "+arr[i]);
  y=n-1;
 for(i=x;i<=y;i++)
 {
  minvalue=arr[i];
  minindex=i;
    for(j=i+1;j<=y;j++)
  {
   if(arr[j]
   {
    minvalue=arr[j];
    minindex=j;
    }
    }
    if(c%2==0)
    {
     t=arr[x];
     arr[x]=minvalue;
     arr[minindex]=t;
     x++;
     }
     else
    {
    t=arr[y];
     arr[y]=minvalue;
     arr[minindex]=t;
     y--;
     i--;
     }
     c++;
     }
     System.out.println("\nFinal elements in the array=");
    for(i=0;i< n;i++)
    System.out.print("   "+arr[i]);
   }
   public static void main(String args[])throws Exception
   {
   Ab1 ob=new Ab1();
   ob.take();
   }
   }


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner