-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlgorithmHelper.cs
More file actions
94 lines (78 loc) · 3.02 KB
/
AlgorithmHelper.cs
File metadata and controls
94 lines (78 loc) · 3.02 KB
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
using System.Collections.Generic;
namespace AlgorithmExamples
{
public static class AlgorithmHelper
{
public static T[] Merge<T>(T[] first, T[] second,
EqualityComparer<T> comparer = null)
{
comparer = comparer ?? EqualityComparer<T>.Default;
var output = new T[first.Length + second.Length];
int firstPointer = 0;
int secondPointer = 0;
int outputPointer = 0;
while (true)
{
var isFirstPointerValid = firstPointer < first.Length;
var isSecondPointerValid = secondPointer < second.Length;
if (!isFirstPointerValid && !isSecondPointerValid)
break;
if (isFirstPointerValid && isSecondPointerValid)
{
if (comparer.Equals(first[firstPointer], second[secondPointer]))
{
output[outputPointer++] = first[firstPointer++];
output[outputPointer++] = second[secondPointer++];
continue;
}
var max = Min(first[firstPointer], second[secondPointer]);
output[outputPointer++] = comparer.Equals(first[firstPointer], max)
? first[firstPointer++]
: second[secondPointer++];
}
else
{
var currentPointer = isFirstPointerValid ? firstPointer : secondPointer;
var array = isFirstPointerValid ? first : second;
for (; currentPointer < array.Length; currentPointer++)
{
output[outputPointer++] = array[currentPointer];
}
break;
}
}
return output;
}
public static void Swap<T>(ref T first, ref T second)
{
var temp = first;
first = second;
second = temp;
}
public static T Max<T>(T x, T y)
{
return (Comparer<T>.Default.Compare(x, y) > 0) ? x : y;
}
public static T Min<T>(T x, T y)
{
return (Comparer<T>.Default.Compare(x, y) < 0) ? x : y;
}
public static bool IsFirstBiggerThanSecond<T>(T first, T second)
{
// null handling.
if (first == null && second == null) return false;
if (first == null) return false;
if (second == null) return true;
var result = Comparer<T>.Default.Compare(first, second);
return result > 0;
}
public static bool IsSecondBiggerThanFirst<T>(T first, T second)
{
if (first == null && second == null) return false;
if (first == null) return true;
if (second == null) return false;
var result = Comparer<T>.Default.Compare(first, second);
return result < 0;
}
}
}