sort a list via divide and conquere in csharp

Here's a simple implementation of MergeSort, which is a divide and conquer algorithm that can be used to sort a list in C#:

main.cs
public static void MergeSort(int[] arr)
{
    if (arr.Length < 2)
        return;
 
    int mid = arr.Length / 2;
    int[] left = new int[mid];
    int[] right = new int[arr.Length - mid];
 
    for (int i = 0; i < mid; i++)
        left[i] = arr[i];
 
    for (int i = mid; i < arr.Length; i++)
        right[i - mid] = arr[i];
 
    MergeSort(left);
    MergeSort(right);
 
    Merge(arr, left, right);
}
 
public static void Merge(int[] arr, int[] left, int[] right)
{
    int i = 0, j = 0, k = 0;
 
    while (i < left.Length && j < right.Length)
    {
        if (left[i] <= right[j])
            arr[k++] = left[i++];
        else
            arr[k++] = right[j++];
    }
 
    while (i < left.Length)
        arr[k++] = left[i++];
 
    while (j < right.Length)
        arr[k++] = right[j++];
}
803 chars
40 lines

This implementation uses recursion to divide the list into two halves, sort them separately, and then merge them back together to produce the final sorted list. The MergeSort function is called repeatedly on each half of the list until the base case (a single-element list) is reached. The Merge function then uses two pointers, i and j, to iterate through the two input arrays, comparing elements and adding them to the output array in order.

To use this implementation, simply call the MergeSort function on your input list:

main.cs
int[] arr = { 3, 7, 4, 5, 2, 1, 6 };
MergeSort(arr);
foreach (int elem in arr)
    Console.Write(elem + " ");
110 chars
5 lines

This will output the sorted list: 1 2 3 4 5 6 7.

gistlibby LogSnag