Monday, February 21, 2011

BlueJ Program on sorting boundary elements of a 2 d array


This program is on sorting the boundary elements of a 2 d array. The number of rows and number of columns of the array may be same or different.

 How to proceed on this boundary elements sorting program

Firstly take all the boundary elements of the 2 d array in an one dimensional array. Next step is to sort the elements of the one dimensional array and then the sorted elements are placed on the boundary locations of the 2 d array.

 Codes of the program

import java.io.*;
class Spiral
{
int x;
int t,r,c,i,j,n,m;
int a[][],b[];
void show()throws IOException
{
t=1;

c=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number of rows:");
n=Integer.parseInt(br.readLine());
System.out.println("enter the number of columns:");
m=Integer.parseInt(br.readLine());

a=new int[n][m];
b=new int[2*(m+n)];
for(i=0;i< n;i++)
{
for(j=0;j< m;j++)
{
System.out.println("enter value:");
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("\nEntered values are\n");
for(i=0;i< n;i++)
{
for(j=0;j< m;j++)
{
System.out.print(" "+a[i][j]);
}
System.out.println();
}
System.out.println("\n\n");
for(i=0;i< m;i++)
{
b[c++]=a[0][i];
}
for(i=1;i< =n-1;i++)
{
b[c++]=a[i][m-1];
}
for(i=m-2;i >=0;i--)
{
b[c++]=a[n-1][i];
}
for(i=n-2;i >0;i--)
{
b[c++]=a[i][0];
}

bsort();
r=0;
c=-1;
t=0;
for(i=1;i<=m;i++)
{
a[r][++c]=b[t++];
}
for(i=1;i<=n-1;i++)
{
a[++r][c]=b[t++];
}
for(i=1;i<=m-1;i++)
{
a[r][--c]=b[t++];
}
for(i=1;i<=n-2;i++)
{
a[--r][c]=b[t++];
}
System.out.println("\nAfter sorting the boundary values\n");
for(i=0;i< n;i++)
{
 for(j=0;j< m;j++)
 {
  System.out.print(" "+a[i][j]);
  }
  System.out.println();
 }

}
private void bsort()
{
 int flag;
 for(i=0;i< c;i++)
 {
  flag=0;
  for(j=0;j< c-i-1;j++)
  {
   if(b[j] >b[j+1])
   {
    flag=1;
    t=b[j];
    b[j]=b[j+1];
    b[j+1]=t;
    }
   }
   if(flag==0)
   break;
  }
  }
public static void main(String args[])throws Exception
{
 Spiral ob=new Spiral();
ob.show();
}
}

5 comments:

  1. how 2 print a " " instead of the middle element

    ReplyDelete
  2. Not clear. Please show it with example.

    ReplyDelete
  3. very complex.i can do it with with better and easy method.

    ReplyDelete
    Replies
    1. Please post the program. Different ideas and logics are welcome.

      Delete

Subscribe via email

Enter your email address:

Delivered by FeedBurner