forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSorter.cs
66 lines (59 loc) · 2.15 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
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Sorters.Comparison
{
/// <summary>
/// Divide and Conquer algorithm, which splits
/// array in two halves, calls itself for the two
/// halves and then merges the two sorted halves.
/// </summary>
/// <typeparam name="T">Type of array elements.</typeparam>
public class MergeSorter<T> : IComparisonSorter<T>
{
/// <summary>
/// Sorts array using merge sort algorithm,
/// originally designed as external sorting algorithm,
/// internal, stable,
/// time complexity: O(n log(n)),
/// space complexity: O(n),
/// where n - array length.
/// </summary>
/// <param name="array">Array to sort.</param>
/// <param name="comparer">Comparer to compare elements of <paramref name="array" />.</param>
public void Sort(T[] array, IComparer<T> comparer)
{
if (array.Length <= 1)
{
return;
}
var (left, right) = Split(array);
Sort(left, comparer);
Sort(right, comparer);
Merge(array, left, right, comparer);
}
private static void Merge(T[] array, T[] left, T[] right, IComparer<T> comparer)
{
var mainIndex = 0;
var leftIndex = 0;
var rightIndex = 0;
while (leftIndex < left.Length && rightIndex < right.Length)
{
var compResult = comparer.Compare(left[leftIndex], right[rightIndex]);
array[mainIndex++] = compResult <= 0 ? left[leftIndex++] : right[rightIndex++];
}
while (leftIndex < left.Length)
{
array[mainIndex++] = left[leftIndex++];
}
while (rightIndex < right.Length)
{
array[mainIndex++] = right[rightIndex++];
}
}
private static (T[] left, T[] right) Split(T[] array)
{
var mid = array.Length / 2;
return (array.Take(mid).ToArray(), array.Skip(mid).ToArray());
}
}
}