I tried to implement a merge sort
in C# and for some reason it gives me a stackoverflow exeption
,I have no idea where it comes from. The error is something small i'm guessing but i can't find it
using System;
class MergeSort
{
public static int maxN = 60;
public static void merge(ref int[] array, int left, int mid, int right)
{
int i, j;
int[] aux = new int[maxN];
for (i = mid + 1; i > left; i--) aux[i - 1] = array[i - 1];
{
for (j = mid; j < right; j++) aux[right + mid - j] = array[j + 1];
{
for (int k = left; k <= right; k++)
{
if (aux[j] < aux[i])
{
array[k] = aux[j--];
}
else
{
array[k] = aux[i++];
}
}
}
}
}
public static void mergeSort(ref int[] array, int l, int r)
{
if (l < r)
{
int m = l + ((r + l) / 2);
mergeSort(ref array, l, m);
mergeSort(ref array, m + 1, r);
merge(ref array, l, m, r);
}
else
return;
}
static void Main()
{
int[] nArray = new int[] { 1, 5, 14, 2, 28, 3, 90, 43, 1, 54, 43, 52 };
Console.WriteLine("Unsorted Array : ");
Console.Write('{');
for (int i = 0; i < nArray.Length; i++)
{
Console.Write("{0}", nArray[i]);
if(i != nArray.Length - 1)
Console.Write(',');
else
Console.WriteLine('}');
}
mergeSort(ref nArray, 0, nArray.Length);
Console.WriteLine("Sorted array :");
Console.Write('{');
for (int i = 0; i < nArray.Length; i++)
{
Console.Write("{0}", nArray[i]);
if (i != nArray.Length - 1)
Console.Write(',');
else
Console.WriteLine('}');
}
}
}
mergeSort
method on the linemergeSort(ref array, l, m);
and see what yourl
,r
andm
values are. I'm sure theStackOverflowException
is becausel < r
is never false. – Nolonar 15 hours agol < r
is alwaystrue
or(2 < 5)
.l
is never increased. – DGibbs 15 hours ago