-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathBoyerMoore.cs
49 lines (40 loc) · 1.17 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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.Search;
/// <summary>
/// A boyer-moore majority finder algorithm implementation.
/// </summary>
public class BoyerMoore<T> where T : IComparable
{
public static T FindMajority(IEnumerable<T> input)
{
var candidate = FindMajorityCandidate(input, input.Count());
if (Verify(input, input.Count(), candidate)) return candidate;
return default;
}
//Find majority candidate
private static T FindMajorityCandidate(IEnumerable<T> input, int length)
{
var count = 1;
var 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 Verify(IEnumerable<T> input, int size, T candidate)
{
return input.Count(x => x.Equals(candidate)) > size / 2;
}
}