Wednesday, April 28, 2010

Binary Search Algorithm

Apparently, only 10 percent of programmers can correctly code the binary search algorithm. What follows is my attempt to prove once and for all that I belong to that select group of programmers! I implemented the algorithm in Excel VBA.
Option Explicit
'++++++++++++++++++++++++++++++++++++++++++++++++
' Author: Ram Limbu
' Date: 2010/04/28
' Description: Binary Search Algorithm in VBA
'++++++++++++++++++++++++++++++++++++++++++++++++

Sub BinaySearch()
Dim UpperLimit As Long
Dim LowerLimit As Long
Dim Mid As Long
Dim Val As Long
Dim NotFound As Boolean
Dim WS As Worksheet

On Error GoTo ErrRtn

'prompt user to enter the number to search
Val = InputBox("Please, enter the number to search")

'set WS to the first Worksheet
Set WS = ThisWorkbook.Worksheets(1)

NotFound = True
LowerLimit = 1

UpperLimit = WS.Cells(65536, 1).End(xlUp).Row

If UpperLimit = 1 And IsEmpty(WS.Cells(1, 1).Value) Then
MsgBox "The Column A on Worksheet1 is empty. Exiting ..."
Exit Sub
End If

While NotFound And LowerLimit <= UpperLimit
Mid = (LowerLimit + UpperLimit) \ 2 ' perform integer division
If Val = WS.Cells(Mid, 1) Then
NotFound = False
ElseIf Val < WS.Cells(Mid, 1) Then
UpperLimit = Mid - 1
Else
LowerLimit = Mid + 1
End If
Wend

If NotFound Then
MsgBox Val & " wasn't found"
Else
WS.Cells(Mid, 1).Select
MsgBox Val & " was found at row " & Mid
End If
Exit Sub
ErrRtn:
MsgBox Err.Description
End Sub

The assumptions are as follows: (1) The data set is pre-ordered and (2) located on Column A of the first Worksheet. To keep the code simple, no data validation is performed.

No comments:

Post a Comment