Working on MergeSort in Java:
public void mergeSort(int[] A)
{
if (A.length > 1)
{
int q = A.length/2;
int[] leftArray = Arrays.copyOfRange(A, 0, q);
int[] rightArray = Arrays.copyOfRange(A,q,A.length);
mergeSort(leftArray);
mergeSort(rightArray);
merge(A,leftArray,rightArray);
}
}
The recursion in the code above works well in Java.
So for curiosity I want to convert function Arrays.copyOfRange from java to c#. Array.copy in C# takes five arguments. Do you know any simpler function in c# do get certain elements of the array starting at position x to y (like java).
In c# I coded the above method like this:
public void mergeSort(int[] A)
{
if (A.Length > 1)
{
int q = A.Length / 2;
int[] leftArray = new int[q];
int[] rightArray = new int[A.Length];
for (int i = 0; i < q; i++)
{
leftArray[i] = A[i];
Console.WriteLine(leftArray[i]);
}
for (int i = q; i < A.Length; i++)
{
rightArray[i] = A[i];
Console.WriteLine(rightArray[i]);
}
Console.ReadKey();
mergeSort(leftArray);
mergeSort(rightArray);
merge(A, leftArray, rightArray);
}
}
As you can see I have replaced Arrays.copyOfRange functions in Java with two loops in c# and this works in c# without recursion. However calling mergeSort(leftArray) and mergeSort(rightArray) it prints this in c#:
Process is terminated due to StackOverflowException!!
Any better idea on how to get certain elements in c#?
copyOfRangehas no direct equivalent in C#, in the sense that C# requires a separate action to create an array, before performing Array.Copy. This is why a newcomer to C# may struggle a bit before seeing a good equivalent. IMHO this question is very useful to some beginners.