- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathMergeSorter.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
usingSystem.Collections.Generic;
usingAlgorithms.Common;
namespaceAlgorithms.Sorting
{
publicstaticclassMergeSorter
{
//
// Public merge-sort API
publicstaticList<T>MergeSort<T>(thisList<T>collection,Comparer<T>comparer=null)
{
comparer=comparer??Comparer<T>.Default;
returnInternalMergeSort(collection,comparer);
}
//
// Private static method
// Implements the recursive merge-sort algorithm
privatestaticList<T>InternalMergeSort<T>(List<T>collection,Comparer<T>comparer)
{
if(collection.Count<2)
{
returncollection;
}
intmidIndex=collection.Count/2;
varleftCollection=collection.GetRange(0,midIndex);
varrightCollection=collection.GetRange(midIndex,collection.Count-midIndex);
leftCollection=InternalMergeSort<T>(leftCollection,comparer);
rightCollection=InternalMergeSort<T>(rightCollection,comparer);
returnInternalMerge<T>(leftCollection,rightCollection,comparer);
}
//
// Private static method
// Implements the merge function inside the merge-sort
privatestaticList<T>InternalMerge<T>(List<T>leftCollection,List<T>rightCollection,Comparer<T>comparer)
{
intleft=0;
intright=0;
intindex;
intlength=leftCollection.Count+rightCollection.Count;
List<T>result=newList<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++]);
}
returnresult;
}
}
}