Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

January 2, 2010

Merge Sort -> Complete Prog

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: