forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BoyerMoore.cs
57 lines (48 loc) · 1.4 KB
/
BoyerMoore.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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Search;
/// <summary>
/// A Boyer-Moore majority finder algorithm implementation.
/// </summary>
/// <typeparam name="T">Type of element stored inside array.</typeparam>
public static class BoyerMoore<T> where T : IComparable
{
public static T? FindMajority(IEnumerable<T> input)
{
var candidate = FindMajorityCandidate(input, input.Count());
if (VerifyMajority(input, input.Count(), candidate))
{
return candidate;
}
return default(T?);
}
// Find majority candidate
private static T FindMajorityCandidate(IEnumerable<T> input, int length)
{
int count = 1;
T candidate = input.First();
foreach (var element in input.Skip(1))
{
if (candidate.Equals(element))
{
count++;
}
else
{
count--;
}
if (count == 0)
{
candidate = element;
count = 1;
}
}
return candidate;
}
// Verify that candidate is indeed the majority
private static bool VerifyMajority(IEnumerable<T> input, int size, T candidate)
{
return input.Count(x => x.Equals(candidate)) > size / 2;
}
}