class Mergesort_Algorithm
{
public void mergesort(int a[],int low, int upper)
{
if (low==upper)
{
return;
}
else
{
int mid=(low+upper)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,upper);
merge(a,low,mid+1,upper);
}
}
public void merge(int a[],int low, int high, int upper)
{
int lower_start=low;
int lower_bound=high-1;
int upper_start=high;
int upper_bound=upper;
int n=upper-low+1;
int i=0;
int sArray[]=new int[n];
while ((lower_start <=lower_bound) && (upper_start<=upper_bound ))
{
if (a[lower_start]<a[upper_start])
{
sArray[i]=a[lower_start++];
i++;
}
else
{
sArray[i]=a[upper_start++];
i++;
}
}
while (lower_start <=lower_bound)
{
sArray[i]=a[lower_start++];
i++;
}
while (upper_start<=upper_bound )
{
sArray[i]=a[upper_start++];
i++;
}
for (i=0;i<n;i++)
{
//System.out.println("-----"+(lower_start-1));
a[low+i]=sArray[i];
}
}
}
class Merge
{
public static void main(String[] args)
{
Mergesort_Algorithm obj=new Mergesort_Algorithm();
int a[] = {2,4,5,9,0,1,7,8,10,6};
//Printing the Given Array.......
System.out.println("Given Array Before Sorting!....");
for(int i=0; i<a.length; i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
obj.mergesort(a, 0, a.length-1);
System.out.println("Given Array Before Sorting!....");
for(int i=0; i<a.length; i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
//System.out.println("Hello World!");
}
}
0 Comments