forked from mstefarov/PASaveEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSorted.cs
40 lines (37 loc) · 1.82 KB
/
MergeSorted.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
using System;
using System.Collections.Generic;
namespace PASaveEditor {
// MergedSorted implementation by Brian Rasmussen @ http://stackoverflow.com/a/9809450
internal static class MergeSortedExtension {
public static IEnumerable<T> MergeSorted<T>(this IEnumerable<T> first, IEnumerable<T> second,
Func<T, T, int> comparer) {
using (var firstEnumerator = first.GetEnumerator()) {
using (var secondEnumerator = second.GetEnumerator()) {
var elementsLeftInFirst = firstEnumerator.MoveNext();
var elementsLeftInSecond = secondEnumerator.MoveNext();
while (elementsLeftInFirst || elementsLeftInSecond) {
if (!elementsLeftInFirst) {
do {
yield return secondEnumerator.Current;
} while (secondEnumerator.MoveNext());
yield break;
}
if (!elementsLeftInSecond) {
do {
yield return firstEnumerator.Current;
} while (firstEnumerator.MoveNext());
yield break;
}
if (comparer(firstEnumerator.Current, secondEnumerator.Current) < 0) {
yield return firstEnumerator.Current;
elementsLeftInFirst = firstEnumerator.MoveNext();
} else {
yield return secondEnumerator.Current;
elementsLeftInSecond = secondEnumerator.MoveNext();
}
}
}
}
}
}
}