Merge Sort Implementation In Java
Sorting Techniques
import java.io.*;
class merge
{
public static int a[];
public static void main(String args[]) throws IOException
{
int n;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter size of array = ");
n = Integer.parseInt(b.readLine());
a = new int[n];
System.out.println("Enter values = ");
for(int i=0;i<n;i++)
a[i] = Integer.parseInt(b.readLine());
merge(0,n-1);
System.out.println(" Sorted Array is = ");
for( int i=0;i<n;i++)
System.out.println(a[i]+" ");
}
public static void simplemerge(int f,int s,int t)
{
int i,j,k,w;
int temp[] = new int[10] ;
i=f; j=s; k=-1;
while(i<=(s-1) && j<=t)
{
if(a[i]<a[j])
temp[++k] =a[i++];
else
temp[++k]=a[j++];
}
if(i>(s-1))
{
for(w=j;w<=t;w++)
temp[++k]=a[w];
}
else
{
for(w=i;w<=s-1;w++)
temp[++k]=a[w];
}
for(w=0;w<=k;w++)
a[f+w]=temp[w];
}
public static void merge(int l, int r)
{
int mid;
if(l<r)
{
mid=(l+r)/2;
merge(l, mid);
merge(mid+1,r);
simplemerge(l, mid+1,r);
}
}
}
class merge
{
public static int a[];
public static void main(String args[]) throws IOException
{
int n;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter size of array = ");
n = Integer.parseInt(b.readLine());
a = new int[n];
System.out.println("Enter values = ");
for(int i=0;i<n;i++)
a[i] = Integer.parseInt(b.readLine());
merge(0,n-1);
System.out.println(" Sorted Array is = ");
for( int i=0;i<n;i++)
System.out.println(a[i]+" ");
}
public static void simplemerge(int f,int s,int t)
{
int i,j,k,w;
int temp[] = new int[10] ;
i=f; j=s; k=-1;
while(i<=(s-1) && j<=t)
{
if(a[i]<a[j])
temp[++k] =a[i++];
else
temp[++k]=a[j++];
}
if(i>(s-1))
{
for(w=j;w<=t;w++)
temp[++k]=a[w];
}
else
{
for(w=i;w<=s-1;w++)
temp[++k]=a[w];
}
for(w=0;w<=k;w++)
a[f+w]=temp[w];
}
public static void merge(int l, int r)
{
int mid;
if(l<r)
{
mid=(l+r)/2;
merge(l, mid);
merge(mid+1,r);
simplemerge(l, mid+1,r);
}
}
}
You Might Also Like :