public class MergeSort
{
private int a[];
public MergeSort(int b[])
{
a = b;
}
public void sort()
{
if(a.length <= 1)
return;
int first[] = new int[a.length / 2];
int second[] = new int[a.length - first.length];
for(int x = 0; x < first.length; x++)
first[x] = a[x];
for(int x = first.length, y = 0; x < a.length; x++, y++)
first[y] = a[x];
//Split the array again
MergeSort sort1 = new MergeSort(first);
MergeSort sort2 = new MergeSort(second);
sort1.sort();
sort2.sort();
merge(first, second);
}
private void merge(int first[], int second[])
{
int x = 0;
int y = 0;
int z = 0;
while(x < first.length && y < second.length)
{
if(first[x] < second[y])
{
a[z] = first[x];
x++;
}
else
{
a[z] = second[y];
y++;
}
z++;
}
//copy remaining elements to the tail of a[];
for(int i = x; i < first.length; i++)
{
a[z] = first[i];
z++;
}
for(int i = y; i < second.length; i++)
{
a[z] = second[i];
z++;
}
}
}
No comments:
Post a Comment