import java.io.*;
class Merge
{
void simplemerge(int a[],int f,int s, int t)
{
int i,j,temp[],k;
temp=new int[t-f+1];
i=f;
j=s;
k=-1;
while (i<=s-1 && j<=t)
{
if (a[i]
temp[++k]=a[i++];
else
temp[++k]=a[j++];
}
for(int w=i;w<=s-1;w++)
{
k++;
temp[k]=a[w];
}
for(int w=0;w<=k;w++)
{
a[f+w]=temp[w];
}
}
void mergesort(int a[],int l,int r)
{
int mid;
if (l
{
mid=(l+r)/2;
mergesort(a,l,mid);
mergesort(a,mid+1,r);
simplemerge(a,l,mid+1,r);
}
}
}
class Test
{
public static void main(String args[])throws Exception
{
DataInputStream d=new DataInputStream(System.in);
System.out.println("How many elements:");
int n=Integer.parseInt(d.readLine());
int a[]=new int[n];
System.out.println("enter the elements:");
for(int i=0;i<=a.length-1;i++)
{
a[i]=Integer.parseInt(d.readLine());
}
Merge m=new Merge();
int l=0;
int r=a.length-1;
m.mergesort(a,l,r);
System.out.println("Sorted Array:");
for(int i=0;i
{
System.out.println(a[i]);
}
}
}
/*Output:
How many elements:
5
enter the elements:
41 38 6 98 57
Sorted Array:
6 38 41 57 98
Process completed.*/
0 comments:
Post a Comment