Uploaded by faxac17068

mergesort

advertisement
MERGE SORT
import java.util.Random;
import java.util.Scanner;
public class Merge
{
static int[] a=new int[500];
static int[] b=new int[500];
static int n;
public static void main(String[] args)
{
Random random=new Random();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the max array size:");
n=sc.nextInt();
for(int i=0;i<n;i++)
{
a[i]=random.nextInt(1000);
}
System.out.println("The unsorted array is");
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
long startTime=System.nanoTime();
mergesort(0,n-1);
long stopTime=System.nanoTime();
long elapsedTime=stopTime-startTime;
System.out.println("The sorted array is");
for(int i=0;i<n;i++)
System.out.println(a[i]+"\t");
System.out.println("Time complexity is
"+elapsedTime);
}
public static void mergesort(int low,int high)
{
if(low<high)
{
int mid=(high+low)/2;
mergesort(low,mid);
mergesort(mid+1,high);
merge(low,mid,high);
}
}
public static void merge(int low,int mid,int high)
{
int i,j,h,k;
h=i=low;
j=mid+1;
while((h<=mid)&& j<=high)
{
if(a[h]>a[j])
b[i++]=a[j++];
else
b[i++]=a[h++];
}
if(h>mid)
for(k=j;k<=high;k++)
b[i++]=a[k];
else
for(k=h;k<=mid;k++)
b[i++]=a[k];
for(k=low;k<=high;k++)
a[k]=b[k];
}
}
Download