MergeSort is a divide-and-conquer algorithm that splits an array into two halves (sub arrays) and recursively sorts each sub array before merging them back into one giant, sorted array.
In this blog, I will provide a simple implementation of MergeSort using C# with comments on every significant line of code for beginners to quickly grasp the algorithm.
Pseudocode
mergeSort(array)
if array.length <= 1 then
return array
left = new array
right = new array
mid = left+ right/2
mergeSort(left)
mergeSort(right)
merge(left, right)
- class MergeSort
- {
- public static int[] mergeSort(int[] array)
- {
- int[] left;
- int[] right;
- int[] result = new int[array.Length];
-
- therfore a stackoverflow
- if (array.Length <= 1)
- return array;
-
- int midPoint = array.Length / 2;
-
- left = new int[midPoint];
-
-
- if (array.Length % 2 == 0)
- right = new int[midPoint];
-
- else
- right = new int[midPoint + 1];
-
- for (int i = 0; i < midPoint; i++)
- left[i] = array[i];
-
- int x = 0;
-
- for (int i = midPoint; i < array.Length; i++)
- {
- right[x] = array[i];
- x++;
- }
-
- left = mergeSort(left);
-
- right = mergeSort(right);
-
- result = merge(left, right);
- return result;
- }
-
-
- public static int[] merge(int[] left, int[] right)
- {
- int resultLength = right.Length + left.Length;
- int[] result = new int[resultLength];
-
- int indexLeft = 0, indexRight = 0, indexResult = 0;
-
- while (indexLeft < left.Length || indexRight < right.Length)
- {
-
- if (indexLeft < left.Length && indexRight < right.Length)
- {
-
- if (left[indexLeft] <= right[indexRight])
- {
- result[indexResult] = left[indexLeft];
- indexLeft++;
- indexResult++;
- }
-
- else
- {
- result[indexResult] = right[indexRight];
- indexRight++;
- indexResult++;
- }
- }
-
- else if (indexLeft < left.Length)
- {
- result[indexResult] = left[indexLeft];
- indexLeft++;
- indexResult++;
- }
-
- else if (indexRight < right.Length)
- {
- result[indexResult] = right[indexRight];
- indexRight++;
- indexResult++;
- }
- }
- return result;
- }
- }
You can now go ahead and call your MergeSort(array) method from Main to see the results.