-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.linq
More file actions
66 lines (54 loc) · 850 Bytes
/
MergeSort.linq
File metadata and controls
66 lines (54 loc) · 850 Bytes
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<Query Kind="Program" />
void Main()
{
var a = new int[]{ 8,7,3,5,0,2,1,6,4};
MergeSort(a).Dump();
}
int[] MergeSort(int[] a)
{
if(a.Length < 2)
{
return a;
}
var left = new int[a.Length / 2];
var right = new int[a.Length - (a.Length / 2)];
Array.Copy(a, left, a.Length / 2);
Array.Copy(a, a.Length / 2, right, 0, a.Length - (a.Length / 2));
return Merge(MergeSort(left), MergeSort(right));
}
int[] Merge(int[] a, int[] b)
{
int i = 0;
int j = 0;
var c = new int[a.Length + b.Length];
for(int k = 0; k < c.Length; k++)
{
if (i < a.Length && j < b.Length)
{
if (i < a.Length && a[i] > b[j])
{
c[k] = b[j];
j++;
}
else
{
c[k] = a[i];
i++;
}
}
else
{
if(i < a.Length)
{
c[k] = a[i];
i++;
}
else
{
c[k] = b[j];
j++;
}
}
}
return c;
}