Merge Sort

import java.util.*;
public class MergeSort
{
public int a[]=new int[50];
public void merge_sort(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}

public void merge(int low,int mid,int high)
{
int h,i,j,k;
int b[]=new int[50];
h=low;
i=low;
j=mid+1;

while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}

public void main()
{
int num,i;
Scanner in = new Scanner(System.in);
System.out.println(“MERGE SORT PROGRAM”);
System.out.println(“Enter the number of elements :”);
num=in.nextInt();
System.out.println(“Enter the (“+ num +”) numbers:”);
for(i=1;i<=num;i++)
{
a[i]=in.nextInt() ;
}
merge_sort(1,num);
System.out.println();
System.out.println(“The sorted list… “);

for(i=1;i<=num;i++)
System.out.print(a[i]+”    “);
}
}

Leave a comment