From c22c481c34b57be74b971c753e690c57f8c391cb Mon Sep 17 00:00:00 2001 From: WildTiger404 Date: Tue, 2 Oct 2018 18:44:51 +0300 Subject: [PATCH] Add recursive Merge Sort --- recursion/MergeSort.cs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 recursion/MergeSort.cs diff --git a/recursion/MergeSort.cs b/recursion/MergeSort.cs new file mode 100644 index 00000000..6e32b6fd --- /dev/null +++ b/recursion/MergeSort.cs @@ -0,0 +1,36 @@ +namespace Merge_Sort +{ + public class MergeSort + { + public static void SortBy(int[] array, int leftBorder, int rightBorder) + { + if (leftBorder >= rightBorder) + return; + int middle = (leftBorder + rightBorder) / 2; + SortBy(array, leftBorder, middle); + SortBy(array, middle+1, rightBorder); + + int[] buf = new int[rightBorder-leftBorder+1]; + + int i = leftBorder; //index of left array + int j = middle + 1; //index of right array + int k = 0; //index of final array + while (i <= middle && j <= rightBorder) + { + if (array[i] < array[j]) + buf[k++] = array[i++]; + else + buf[k++] = array[j++]; + } + //Add the tail of right array + while (j <= rightBorder) + buf[k++] = array[j++]; + //Add the tail of left array + while (i <= middle) + buf[k++] = array[i++]; + + for (k = 0; k < rightBorder - leftBorder + 1; k++) + array[leftBorder + k] = buf[k]; + } + } +}