■ 문자열 이진 탐색하기 예제

----------------------------------------------------------------------------------------------------

Dim strValueArray(1 To 100) As String

Dim nIndex                  As Integer

Dim I                       As Integer

 

For I = 1 To 100

 

    strValueArray(I) = "D" & Right("000" & I, 3)

 

Next

 

nIndex = BinarySearch(strValueArray, "D083")

 

If nIndex > -1 Then

 

    Print nIndex

 

Else

 

    Print "Not found"

    

End If

----------------------------------------------------------------------------------------------------

 

■ 문자열 이진 탐색하기

----------------------------------------------------------------------------------------------------

' 이진 탐색하기

' strValueArray : 값 배열

' strSearch     : 검색 문자열

' 반환값        : 인덱스, -1인 경우 찾는 항목이 없음

Public Function BinarySearch(strValueArray() As String, strSearch As String) As Integer

 

    Dim nFirstIndex  As Integer

    Dim nLastIndex   As Integer

    Dim nMiddleIndex As Integer

    

    

    nFirstIndex = LBound(strValueArray)

    

    nLastIndex = UBound(strValueArray)

    

    

    Do While nFirstIndex <= nLastIndex

    

        nMiddleIndex = (nFirstIndex + nLastIndex) / 2

        

        If strSearch = strValueArray(nMiddleIndex) Then

        

            BinarySearch = nMiddleIndex

            

            Exit Function

            

        Else

        

            If strSearch < strValueArray(nMiddleIndex) Then

            

                nLastIndex = nMiddleIndex - 1

            

            Else

            

                nFirstIndex = nMiddleIndex + 1

            

            End If

        

        End If

    

    Loop

 

    BinarySearch = -1

 

End Function

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG

댓글을 달아 주세요