forked from ambujraj/hacktoberfest2018
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort.cs
36 lines (33 loc) · 1.18 KB
/
MergeSort.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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];
}
}
}