#Region "Dict vs bin"
Private Sub Button15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button15.Click
Debug.WriteLine("Dictionary, Sorted")
Search("dict", 7747401, True)
Search("dict", CInt(Rnd() * 10000000), True)
Debug.WriteLine("")
Debug.WriteLine("Dictionary, Unsorted")
Search("dict", 7747401, False)
Search("dict", CInt(Rnd() * 10000000), False)
Debug.WriteLine("")
End Sub
Private Sub Button16_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button16.Click
Debug.WriteLine("Binary, Sorted")
Search("bin", 7747401, True)
Search("bin", CInt(Rnd() * 10000000), True)
Debug.WriteLine("")
End Sub
Private Sub Search(ByVal mode As String, ByVal value As Integer, ByVal sorted As Boolean)
Dim dict As New Dictionary(Of Integer, Integer)
If Not sorted And mode = "bin" Then Throw New Exception("Binary search MUST be sorted.")
Dim FirstTic As Integer = Environment.TickCount
If Not IO.File.Exists("C:\DictVsBinTest.xml") Then GenerateRandomData()
Dim ds As New DataSet
ds.ReadXml("C:\DictVsBinTest.xml")
Dim drs() As DataRow
If sorted Then
drs = ds.Tables(0).Select("", "ID Asc")
Else
drs = ds.Tables(0).Select
End If
Dim IDs(drs.Length - 1) As Integer
Dim i As Integer
For Each dr As DataRow In drs
If mode = "bin" Then
IDs(i) = CInt(dr("ID"))
Else
dict.Add(i, CInt(dr("ID")))
End If
i += 1
Next
Dim result As Boolean
Dim EndTic As Integer
Dim StartTic As Integer = Environment.TickCount
If mode = "bin" Then
result = BinarySearch(value, IDs)
Else
result = dict.ContainsValue(value)
End If
EndTic = Environment.TickCount
If result Then
Debug.WriteLine(value & " Found in " & EndTic - StartTic & " ticks")
Debug.WriteLine("Total Time: " & EndTic - FirstTic & " ticks")
Else
Debug.WriteLine(value & " Not found in " & EndTic - StartTic & " ticks")
Debug.WriteLine("Total Time: " & EndTic - FirstTic & " ticks")
End If
End Sub
Private Function BinarySearch(ByVal Value As Integer, ByVal Array As Integer()) As Boolean
Dim ReturnValue As Boolean = False
Dim Top As Integer = Array.Length - 1
Dim Bottom As Integer = 0
Dim CompValue As Integer
Dim pot As Integer
Do
pot = ((Top - Bottom) \ 2) + Bottom
CompValue = Array(pot)
If Value > CompValue Then
Bottom = pot + 1
ElseIf Value < CompValue Then
Top = pot
Else
ReturnValue = True
End If
Loop Until ReturnValue = True Or Top = Bottom
Return ReturnValue
End Function
Private Sub GenerateRandomData()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
dt.Columns.Add("ID", GetType(Integer))
For i As Integer = 0 To 500000
Dim ID As Integer = CInt(Rnd() * Integer.MaxValue)
Dim dr As DataRow = dt.NewRow
dr("ID") = ID
dt.Rows.Add(dr)
Next
ds.WriteXml("C:\DictVsBinTest.xml", XmlWriteMode.WriteSchema)
End Sub
#End Region