-
Notifications
You must be signed in to change notification settings - Fork 8
/
Searching.cs
101 lines (86 loc) · 2.66 KB
/
Searching.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
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
95
96
97
98
99
100
101
using System.Diagnostics;
namespace Arrays;
public class Searching
{
public static void SearchWithIndexOf(string[] myRecentFiles, string openedFile)
{
int recentFileListIndex = Array.IndexOf(myRecentFiles, openedFile);
if (recentFileListIndex < 0)
{
AddNewRecentEntry(openedFile);
}
else
{
MoveExistingRecentEntryToTop(recentFileListIndex);
}
}
public static int GetIndexOfFirstNonEmptyBin(int[] bins)
=> Array.FindIndex(bins, IsNonZero);
private static bool IsNonZero(int value) => value != 0;
public class WithLambda
{
public static int GetIndexOfFirstNonEmptyBin(int[] bins)
=> Array.FindIndex(bins, value => value != 0);
}
public static T[] GetNonNullItems<T>(T[] items) where T : class
=> Array.FindAll(items, value => value != null);
public static void SearchPerf()
{
var sw = new Stopwatch();
int[] big = new int[100_000_000];
Console.WriteLine("Initializing");
sw.Start();
var r = new Random(0);
for (int i = 0; i < big.Length; ++i)
{
big[i] = r.Next(big.Length);
}
sw.Stop();
Console.WriteLine(sw.Elapsed.ToString("s\\.f"));
Console.WriteLine();
Console.WriteLine("Searching");
for (int i = 0; i < 6; ++i)
{
int searchFor = r.Next(big.Length);
sw.Reset();
sw.Start();
int index = Array.IndexOf(big, searchFor);
sw.Stop();
Console.WriteLine($"Index: {index}");
Console.WriteLine($"Time: {sw.Elapsed:s\\.ffff}");
}
Console.WriteLine();
Console.WriteLine("Sorting");
sw.Reset();
sw.Start();
Sort(big);
sw.Stop();
Console.WriteLine(sw.Elapsed.ToString("s\\.ff"));
Console.WriteLine();
Console.WriteLine("Searching (binary)");
for (int i = 0; i < 6; ++i)
{
int searchFor = r.Next() % big.Length;
sw.Reset();
sw.Start();
int index = Find(big, searchFor);
sw.Stop();
Console.WriteLine($"Index: {index}");
Console.WriteLine($"Time: {sw.Elapsed:s\\.fffffff}");
}
void Sort(int[] numbers)
{
Array.Sort(numbers);
}
int Find(int[] numbers, int searchFor)
{
return Array.BinarySearch(numbers, searchFor);
}
}
private static void MoveExistingRecentEntryToTop(int recentFileListIndex)
{
}
private static void AddNewRecentEntry(string openedFile)
{
}
}