-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.cs
More file actions
62 lines (53 loc) · 1.61 KB
/
Copy pathMergeSort.cs
File metadata and controls
62 lines (53 loc) · 1.61 KB
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
using System;
using Tracker;
namespace Sorting
{
public class MergeSort<T> : Tracker<T>, ISorter<T>
where T : IComparable<T>
{
public void Sort(T[] items)
{
if (items.Length <= 1)
{
return;
}
int leftSize = items.Length / 2;
int rightSize = items.Length - leftSize;
T[] left = new T[leftSize];
T[] right = new T[rightSize];
Array.Copy(items, 0, left, 0, leftSize);
Array.Copy(items, leftSize, right, 0, rightSize);
Sort(left);
Sort(right);
Merge(items, left, right);
}
private void Merge(T[] items, T[] left, T[] right)
{
int leftIndex = 0;
int rightIndex = 0;
int targetIndex = 0;
int remaining = left.Length + right.Length;
while(remaining > 0)
{
if (leftIndex >= left.Length)
{
Assign(items, targetIndex, right[rightIndex++]);
}
else if (rightIndex >= right.Length)
{
Assign(items, targetIndex, left[leftIndex++]);
}
else if (Compare(left[leftIndex], right[rightIndex]) < 0)
{
Assign(items, targetIndex, left[leftIndex++]);
}
else
{
Assign(items, targetIndex, right[rightIndex++]);
}
targetIndex++;
remaining--;
}
}
}
}