Jump to content

Binary search Algorithm

- - - - -

  • Please log in to reply
No replies to this topic

#1
jerry4prince

jerry4prince

    Newbie

  • Members
  • Pip
  • 1 posts
Pls i am working on binary search and i having some error with my codes

Run-time '63':
Bad record number


Private Function BinarySearch(strSearchItem As String) As Long

Dim lngFirst As Long

Dim lngLast As Long

Dim lngMiddle As Long

Dim lngLastPass As Long

Dim strItem As String

Dim strValue As String

Dim blnDone As Boolean


    Open "TDStudList.txt" For Random As 1 Len = Len(StudRec)

    Rec = LOF(1) / Len(StudRec)

    

    lngFirst = 1

    lngLast = Rec

    strItem = UCase$(Trim$(strSearchItem))

    

    'If there is only one record check if it is the desired one.

    

    If lngLast = 1 Then

        Get 1, 1, StudRec

        If strItem = UCase$(StudRec.RegNO) Then

            BinarySearch = 1

        Else

            BinarySearch = 0

        End If

        Close 1

        Exit Function

    End If

    

    'Set the pointer to the middle record.

    

    lngMiddle = ((lngLast - lngFirst) + 1) \ 2

    

    Do Until blnDone

    

        Get 1, lngMiddle, StudRec

        strValue = UCase$(StudRec.RegNO)

        If strItem = strValue Then

            '

            'Item Found

            '

            BinarySearch = lngMiddle

            blnDone = True

            Exit Do

        ElseIf strItem < strValue Then

            '

            'Direction = Down

            'Remove the second half of the records

            

            lngLast = lngMiddle

            lngMiddle = lngMiddle - ((lngLast - lngFirst) + 1) \ 2

        ElseIf strItem > strValue Then

            '

            'Direction = UP

            'Remove the first half of the records

            '

            lngFirst = lngMiddle

            lngMiddle = lngMiddle - ((lngLast - lngFirst) + 1) \ 2

        End If

        '

        'Check if the records are still divisible

        '

        If (lngMiddle = lngFirst) Or (lngMiddle = lngLast) Then

            lngLastPass = lngLastPass + 1

            If lngLastPass = 2 Then

            lngLastPass = 0

            BinarySearch = 0

            blnDone = True

            End If

        End If

        Loop

        

    Close 1

               

End Function





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users