Sunday, 17 December 2017

Merge Sorting in Java

Apply Merge Sort on Data and print the Sorted Data

Program:


import java.util.Scanner;
class merge{
      public static void main(String arg[]){
          Scanner sc=new Scanner(System.in);
          int i,j,tmp;
  int a[]=new int[5];
  System.out.println("Enter numbers is array:");
  for(i=0;i<5;i++)
 {
a[i]=sc.nextInt();
 }
 mm m1=new mm();
 m1.merge_sort(a,0,5-1);
 for(i=0;i<5;i++)
{
System.out.println("sorted array:"+a[i]);
}
    }
}
class mm{
     void merge_sort(int a[],int beg,int end)
    {
    int mid;
   if(beg<end)
{
mid=(beg+end)/2;
merge_sort(a,beg,mid);
merge_sort(a,mid+1,end);
merge1(a,beg,mid,end);
 }
     }
     void merge1(int a[],int beg,int mid,int end)
    {
   int i,j,index,k;
   int tmp[]=new int[5];
     i=beg;
   j=mid+1;
   index=beg;
   while(i<=mid && j<=end)
  {
if(a[i]<a[j])
{
tmp[index]=a[i];
i=i+1;
}
else
{
tmp[index]=a[j];
j=j+1;
}
index=index+1;
 }
 if(i>mid)
{
        while(j<=end)
{
tmp[index]=a[j];
index=index+1;
j=j+1;
}
  }
else
{
while(i<=mid)
{
tmp[index]=a[i];
i=i+1;
index=index+1;
}
}
for(k=beg;k<index;k++)
a[k]=tmp[k];
   }


OUTPUT:





No comments:

Post a Comment