Saturday, May 14, 2011

BueJ program on arranging an array with highest number in middle second highest to right and so on


We will take 10 numbers from the user and the numbers will be arranged in this program in such a manner that the highest number will be at the middle, next number wil be at the right side of the highest number and next will be at the left of the highest number and so on.

Here is the codes of the program

import java.io.*;
class ArrangeNumbers
{
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 int arr[]=new int [10];
 int arrange[]=new int[10];
 int i,j,flag,t,x;
 public void take() throws Exception
 {
  for(i=0;i< 10;i++)
  {
   System.out.println("Number:");
   arr[i]=Integer.parseInt(br.readLine());
  }
  System.out.println("\nEntered values are\n");
  for(i=0;i< 10;i++)
  {
   System.out.print(" "+arr[i]);
  }

   for(i=0;i< 10;i++)
   {
    flag=0;
    for(j=0;j< 10-i-1;j++)
    {
    if(arr[j] < arr[j+1])
    {
     flag=1;
     t=arr[j];
     arr[j]=arr[j+1];
     arr[j+1]=t;
     }
     }
     if(flag==0)
     break;
     }
     arrangeValues();
  }
  private void arrangeValues()
  {
  int right,left;
   x=(0+9)/2;
   right=x+1;
   left=x-1;
   for(i=0;i< 10;i++)
   {
    arrange[x]=arr[i];
    if(i%2==0)
    {
     x=right;
    right++;
    }
    else
    {
    x=left;
    left--;
    }
    }
  System.out.println("\nArranged values are\n");
  for(i=0; i< 10;i++)
  {
   System.out.print(" "+arrange[i]);
  }
 }
 public static void main(String args[])throws Exception
 {
  ArrangeNumbers ob=new ArrangeNumbers();
  ob.take();
  }
Technical analysis of the program

Firstly the numbers are entered in an array and they are sorted in decending order using bubble sort and I think upto this point no explanation is required. If you have any question, how bubble sorting technique works, go through bubble sort technique in this blog. I have used three variables x, left and right in this program to set the numbers in locations and to access the left and right locations. Initial values of ‘x’ is set to the middle location of the array and value of right is just ‘x+1’ and that of left is ‘x-1’. As the array is arranged in decending order, the first number is the highest value and that is set at the middle location of another array ‘arrange’. Within the loop where the numbers are arranged, alternately ‘left’ is decreased by 1 and ‘right’ is increased by 1. Values of ‘left’ and ‘right’ is set on ‘x’ and the numbers from the arranged array is shifted to another array.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner