forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExternalMergeSorter.cs
123 lines (108 loc) · 3.7 KB
/
ExternalMergeSorter.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
using System;
using System.Collections.Generic;
namespace Algorithms.Sorters.External
{
public class ExternalMergeSorter<T> : IExternalSorter<T>
{
public void Sort(
ISequentialStorage<T> mainMemory,
ISequentialStorage<T> temporaryMemory,
IComparer<T> comparer)
{
var originalSource = mainMemory;
var source = mainMemory;
var temp = temporaryMemory;
var totalLength = mainMemory.Length;
for (var stripLength = 1L; stripLength < totalLength; stripLength *= 2)
{
using var left = source.GetReader();
using var right = source.GetReader();
using var output = temp.GetWriter();
for (var i = 0L; i < stripLength; i++)
{
right.Read();
}
Merge(left, right, output, stripLength, Math.Min(stripLength, totalLength - stripLength), comparer);
var step = 2 * stripLength;
long rightStripStart;
for (rightStripStart = stripLength + step; rightStripStart < mainMemory.Length; rightStripStart += step)
{
for (var i = 0L; i < stripLength; i++)
{
left.Read();
right.Read();
}
Merge(left, right, output, stripLength, Math.Min(stripLength, totalLength - rightStripStart), comparer);
}
for (var i = 0L; i < totalLength + stripLength - rightStripStart; i++)
{
output.Write(right.Read());
}
(source, temp) = (temp, source);
}
if (source == originalSource)
{
return;
}
using var sorted = source.GetReader();
using var dest = originalSource.GetWriter();
for (var i = 0; i < totalLength; i++)
{
dest.Write(sorted.Read());
}
}
private static void Merge(
ISequentialStorageReader<T> left,
ISequentialStorageReader<T> right,
ISequentialStorageWriter<T> output,
long leftLength,
long rightLength,
IComparer<T> comparer)
{
var leftIndex = 0L;
var rightIndex = 0L;
var l = left.Read();
var r = right.Read();
while (true)
{
if (comparer.Compare(l, r) < 0)
{
output.Write(l);
leftIndex++;
if (leftIndex == leftLength)
{
break;
}
l = left.Read();
}
else
{
output.Write(r);
rightIndex++;
if (rightIndex == rightLength)
{
break;
}
r = right.Read();
}
}
if (leftIndex < leftLength)
{
output.Write(l);
Copy(left, output, leftLength - leftIndex - 1);
}
if (rightIndex < rightLength)
{
output.Write(r);
Copy(right, output, rightLength - rightIndex - 1);
}
}
private static void Copy(ISequentialStorageReader<T> from, ISequentialStorageWriter<T> to, long count)
{
for (var i = 0; i < count; i++)
{
to.Write(from.Read());
}
}
}
}