1

I am trying to implement a merge-sort in c# to try and learn the language. I am having trouble splitting the array in the divide step. I come from a c background and would do something like this:

void MergeSort(int array[], int size)
{
    if (size == 1) 
        return;
    MergeSort(array, size/2);
    MergeSort(array + size/2, size - size/2);
}

My question is, can you do something similar in c#? I am aware there is take and skip methods, but is this the best way?

4
  • 1
    Several things - you can use List<int> instead of the array (it is a class, so the reference is what gets passed, by value). And though you can use pointers with unsafe, that's not really the C# way. Commented Mar 24, 2013 at 12:08
  • @oded So in c# is an array a value type? Commented Mar 24, 2013 at 12:13
  • My point was more that for resizing it is more appropriate. Arrays are not used as often as other collection types in C#. Arrays are reference types. Commented Mar 24, 2013 at 12:14
  • using pointers is possible in c#, but it is one of the more advaned features of the language. if you start learning, you should use the direct addressing Commented Mar 24, 2013 at 12:15

2 Answers 2

9

Use indexes instead of pointers.

void MergeSort(int[] array, int startIndex, int endIndex){
...
}
Sign up to request clarification or add additional context in comments.

Comments

2

Perhaps you could pass the index you want to use to the function:

private static void MergeSort(int[] array, int size, int index) {
    if (size == 1) {
        return;
    }
    MergeSort(array, size / 2, index);
    MergeSort(array, size - size / 2, index + size / 2);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.