forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSorter.cs
105 lines (87 loc) · 3.31 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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, 0, collection.Count - 1, comparer);
}
//
// Private static method
// Implements the recursive merge-sort algorithm
private static List<T> InternalMergeSort<T>(List<T> collection, int startIndex, int endIndex, Comparer<T> comparer)
{
if (collection.Count < 2)
{
return collection;
}
else if (collection.Count == 2)
{
if (comparer.Compare(collection[endIndex], collection[startIndex]) < 0)
{
collection.Swap(endIndex, startIndex);
}
return collection;
}
else
{
int midIndex = collection.Count / 2;
var leftCollection = collection.GetRange(startIndex, midIndex);
var rightCollection = collection.GetRange(midIndex, (endIndex - midIndex) + 1);
leftCollection = InternalMergeSort<T>(leftCollection, 0, leftCollection.Count - 1, comparer);
rightCollection = InternalMergeSort<T>(rightCollection, 0, rightCollection.Count - 1, 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; index < length; ++index)
{
if (right < rightCollection.Count && comparer.Compare(rightCollection[right], leftCollection[left]) <= 0) // rightElement <= leftElement
{
//resultArray.Add(rightCollection[right]);
result.Insert(index, rightCollection[right]);
right++;
}
else
{
//result.Add(leftCollection[left]);
result.Insert(index, leftCollection[left]);
left++;
if (left == leftCollection.Count)
break;
}
}
//
// Either one might have elements left
int rIndex = index + 1;
int lIndex = index + 1;
while (right < rightCollection.Count)
{
result.Insert(rIndex, rightCollection[right]);
rIndex++;
right++;
}
while (left < leftCollection.Count)
{
result.Insert(lIndex, leftCollection[left]);
lIndex++;
left++;
}
return result;
}
}
}