by Anonymous (267 Submissions)
Category: Internet/HTML
Compatability: VB 6.0
Difficulty: Unknown Difficulty
Originally Published: Sun 31st March 2002
Date Added: Mon 8th February 2021
Rating: (1 Votes)
Code demonstrates a binary search, excellent for beginning VB programmers
' Demonstrating a binary search
Option Explicit
Option Base 1
Dim mArray(15) As Integer
Dim mLowBound As Integer
Dim mUpperBound As Integer
Private Sub Form_Load()
Dim x As Integer
mLowBound = LBound(mArray)
mUpperBound = UBound(mArray)
' Generate some array data
For x = mLowBound To mUpperBound
mArray(x) = 2 * x
Next x
End Sub
Private Sub cmdSearch_Click()
Dim x As Integer
Call Cls
' Print blanks so printing does not
' print behind Label and TextBox
For x = 1 To 5
Print
Next x
Call BinarySearch
End Sub
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
If (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Private Sub PrintHeader()
Dim x As Integer
Print "Indexes:"
For x = mLowBound To mUpperBound
Print Format$(x, "!@@@@");
Next x
Print
For x = mLowBound To 4 * mUpperBound
Print "-";
Next x
Print
End Sub
Private Sub PrintRow(low As Integer, middle As Integer, _
high As Integer)
Dim x As Integer
For x = mLowBound To mUpperBound
If (x < low Or x > high) Then
Print Space$(4);
ElseIf (x = middle) Then
Print Format$(mArray(x) & "*", "!@@@@");
Else
Print Format$(mArray(x), "!@@@@");
End If
Next x
Print
End Sub
No comments have been posted about Code demonstrates a binary search, excellent for beginning VB programmers. Why not be the first to post a comment about Code demonstrates a binary search, excellent for beginning VB programmers.