-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
MergeSorter.cs
83 lines (66 loc) · 2.59 KB
/
MergeSorter.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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System.Collections.Generic;
using Algorithms.Common;
namespace Algorithms.Sorting
{
public static class MergeSorter
{
//
// Public merge-sort API
public static List<T> MergeSort<T>(this List<T> collection, Comparer<T> comparer = null)
{
comparer = comparer ?? Comparer<T>.Default;
return InternalMergeSort(collection, comparer);
}
//
// Private static method
// Implements the recursive merge-sort algorithm
private static List<T> InternalMergeSort<T>(List<T> collection, Comparer<T> comparer)
{
if (collection.Count < 2)
{
return collection;
}
int midIndex = collection.Count / 2;
var leftCollection = collection.GetRange(0, midIndex);
var rightCollection = collection.GetRange(midIndex, collection.Count - midIndex);
leftCollection = InternalMergeSort<T>(leftCollection, comparer);
rightCollection = InternalMergeSort<T>(rightCollection, comparer);
return InternalMerge<T>(leftCollection, rightCollection, comparer);
}
//
// Private static method
// Implements the merge function inside the merge-sort
private static List<T> InternalMerge<T>(List<T> leftCollection, List<T> rightCollection, Comparer<T> comparer)
{
int left = 0;
int right = 0;
int index;
int length = leftCollection.Count + rightCollection.Count;
List<T> result = new List<T>(length);
for (index = 0; right < rightCollection.Count && left < leftCollection.Count; ++index)
{
if (comparer.Compare(rightCollection[right], leftCollection[left]) <= 0) // rightElement <= leftElement
{
//resultArray.Add(rightCollection[right]);
result.Insert(index, rightCollection[right++]);
}
else
{
//result.Add(leftCollection[left]);
result.Insert(index, leftCollection[left++]);
}
}
//
// At most one of left and right might still have elements left
while (right < rightCollection.Count)
{
result.Insert(index++, rightCollection[right++]);
}
while (left < leftCollection.Count)
{
result.Insert(index++, leftCollection[left++]);
}
return result;
}
}
}