Tuesday, February 9, 2010

Algorithms - MergeSort in C#

Hi All,

Today I was working on small algorithm to sort array using MergeSort. I wrote this program in C#. Putting it here in case anybody want to use it feel free to use.

I used Generic methods here so that input can be any type as long as it uses IComparable interface.

public class MergeSortAlgo
{
public void Merge(ref T[] initialArray) where T : IComparable
{
if (initialArray == null || initialArray.Length == 0)
return;

T[] temp = new T[initialArray.Length];

MSort(ref temp, ref initialArray, 0, initialArray.Length - 1);

}

private void MSort(ref T[] temp, ref T[] initialArray, int start, int end) where T:IComparable
{
if (end - start > 0)
{
this.MSort(ref temp, ref initialArray, start, (end + start) / 2);
this.MSort(ref temp, ref initialArray, (end + start) / 2 + 1, end);
this.MergeSort(ref temp, ref initialArray, start, (end + start) / 2 + 1, end);
}
}

private void MergeSort(ref T[] temp, ref T[] initialArray, int start, int mid, int end) where T:IComparable
{
int i = start;
int j = mid;
int pos = start;

while (i != mid || j != end + 1)
{
if(i == mid)
{
for (; j <= end; j++)
{
temp[pos] = initialArray[j];
pos++;
}

break;
}
else if(j == end + 1)
{
for (; i < mid; i++)
{
temp[pos] = initialArray[i];
pos++;
}

break;
}

if (initialArray[i].CompareTo(initialArray[j]) <= 0)
{
temp[pos] = initialArray[i];
pos++;
i++;
}
else if (initialArray[i].CompareTo(initialArray[j]) > 0)
{
temp[pos] = initialArray[j];
pos++;
j++;
}
}

for (int counter = start; counter <= end; counter++)
{
initialArray[counter] = temp[counter];
}
}
}

No comments:

Post a Comment