create mergesort in csharp in csharp

Here's an implementation of MergeSort in C#:

main.cs
public static void MergeSort(int[] arr)
{
    MergeSort(arr, 0, arr.Length - 1);
}

private static void MergeSort(int[] arr, int left, int right)
{
    if (left < right)
    {
        int middle = (left + right) / 2;
        MergeSort(arr, left, middle);
        MergeSort(arr, middle + 1, right);
        Merge(arr, left, middle, right);
    }
}

private static void Merge(int[] arr, int left, int middle, int right)
{
    int[] temp = new int[right - left + 1];
    int i = left;
    int j = middle + 1;
    int k = 0;

    while (i <= middle && j <= right)
    {
        if (arr[i] <= arr[j])
        {
            temp[k] = arr[i];
            i++;
        }
        else
        {
            temp[k] = arr[j];
            j++;
        }

        k++;
    }

    while (i <= middle)
    {
        temp[k] = arr[i];
        i++;
        k++;
    }

    while (j <= right)
    {
        temp[k] = arr[j];
        j++;
        k++;
    }

    for (int x = 0; x < temp.Length; x++)
    {
        arr[left + x] = temp[x];
    }
}
1030 chars
59 lines

To use this implementation, you can simply call MergeSort and pass in your array of integers:

main.cs
int[] arr = new int[] {4, 2, 10, 5, 7, 1, 3, 6, 9, 8};
MergeSort(arr);
71 chars
3 lines

After the call to MergeSort, arr will be sorted in ascending order.

gistlibby LogSnag