import java.io.*;
class merge
{
static DataInputStream d = new DataInputStream(System.in);
int a[],n;
public void insert()throws IOException
{
System.out.println("Enter array size : ");
n=Integer.parseInt(d.readLine());
a=new int[n];
System.out.println("Enter the elements");
for(int i=0;i<n;++i)
a[i]=Integer.parseInt(d.readLine());
}
class merge
{
static DataInputStream d = new DataInputStream(System.in);
int a[],n;
public void insert()throws IOException
{
System.out.println("Enter array size : ");
n=Integer.parseInt(d.readLine());
a=new int[n];
System.out.println("Enter the elements");
for(int i=0;i<n;++i)
a[i]=Integer.parseInt(d.readLine());
}
public void display()
{
System.out.println("\n\nThe sorted array is :");
for (int i=0;i<n;i++)
{
System.out.println(a[i]);
}}
public void mergesort()throws IOException
{
int workspace[]=new int[n];
recmerge(workspace,0,n-1);
}
public void recmerge(int[]workspace,int l,int u)throws IOException
{
if (l==u)
return;
else
{
int mid=(l+u)/2;
recmerge(workspace,l,mid);
recmerge(workspace,mid+1,u);
merge(workspace,l,mid+1,u);
}
}
public void merge(int workspace[],int lptr,int hptr,int u)throws IOException
{
int j=0;
int l=lptr;
int mid=hptr-1;
int n=u-l+1;
while(lptr<=mid && hptr<=u)
if (a[lptr]<a[hptr])
workspace[j++]=a[lptr++];
else
workspace[j++]=a[hptr++];
while(lptr<=mid)
workspace[j++]=a[lptr++];
while(hptr<=u)
workspace[j++]=a[hptr++];
for(j=0;j<n;j++)
a[l+j]=workspace[j];
}
}
class Boss
{
public static void main(String args[])throws IOException
{
merge arr=new merge();
arr.insert();
arr.mergesort();
arr.display();
}}
0 comments:
Post a Comment