-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
71 lines (59 loc) · 1.73 KB
/
Program.cs
File metadata and controls
71 lines (59 loc) · 1.73 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
using System;
using System.Diagnostics;
using System.Net;
namespace SearchAlgorithms
{
class Program
{
static void Main()
{
var words = new WebClient()
.DownloadString(@"https://raw.githubusercontent.com/dwyl/english-words/master/words.txt")
.Split('\n');
RunTest(words, LinearSearch);
RunTest(words, BinarySearch);
//RunTest(words, (list, target) => Array.IndexOf(list, target));
//RunTest(words, (list, target) => Array.BinarySearch(list, target));
Console.ReadLine();
}
private static void RunTest(string[] words, Action<string[], string> searchAlgorithm)
{
const int numberOfTests = 10000;
var random = new Random();
var stopwatch = new Stopwatch();
for (int i = 0; i < numberOfTests; i++)
{
var randomTarget = words[random.Next(0, words.Length)];
stopwatch.Start();
searchAlgorithm(words, randomTarget);
stopwatch.Stop();
}
Console.WriteLine($"{searchAlgorithm.Method.Name}, total time: {stopwatch.ElapsedMilliseconds}ms");
}
private static void LinearSearch(string[] words, string target)
{
foreach (string word in words)
{
if (word == target) return;
}
}
private static void BinarySearch(string[] words, string target)
{
int lowerBound = 0;
int upperBound = words.Length - 1;
int middle = upperBound / 2;
while (words[middle] != target)
{
if (String.Compare(words[middle], target, StringComparison.Ordinal) > 0)
{
upperBound = middle - 1;
}
else
{
lowerBound = middle + 1;
}
middle = lowerBound + (upperBound - lowerBound) / 2;
}
}
}
}