Performing a Binary Search through an Array : Array Sort « Data Type « VBA / Excel / Access / Word






Performing a Binary Search through an Array

 
  Option Explicit
  Option Base 1

  Sub Binary_Search_of_Array()
      Dim intThousand(1000) As Integer
      Dim i As Integer
      Dim intTop As Integer
      Dim intMiddle As Integer
      Dim intBottom As Integer
      Dim varUserNumber As Variant

      For i = 1 To 1000
          intThousand(i) = i
      Next i

      varUserNumber = 233
      intTop = UBound(intThousand)
      intBottom = LBound(intThousand)

      Do
          intMiddle = (intTop + intBottom) / 2
          If varUserNumber > intThousand(intMiddle) Then
             intBottom = intMiddle + 1
          Else
              intTop = intMiddle - 1
          End If
      Loop Until (varUserNumber = intThousand(intMiddle)) _
          Or (intBottom > intTop)

      If varUserNumber = intThousand(intMiddle) Then
          Debug.Print varUserNumber & ", at position " & intMiddle 
      Else
          Debug.Print "not in "
      End If
  End Sub

 








Related examples in the same category

1.VBA Bubble Sort
2.using dynamic arrays in bubble sort
3.Quick sort
4.Quick Sort 2