普通版

Module Module1
    Sub Main()
        Dim x() As Integer = {0, 5, 6, 8, 9}
        Dim search, high, low, mid As Integer
        search = Console.ReadLine()
        low = 0
        high = 4
        mid = (low + high) / 2

        While (low <= high)
            If (x(mid) = search) Then
                Console.Write(mid)
                Exit While
            ElseIf (x(mid) > search) Then
                high = mid - 1
            ElseIf (x(mid) < search) Then
                low = mid + 1
            End If
            mid = (low + high) / 2
        End While

        If (x(mid) <> search) Then
            Console.Write(-1)
        End If

        Console.ReadKey()
    End Sub
End Module

 

遞迴版

Module Module1
    Dim x() As Integer = {0, 5, 6, 8, 9}

Sub Main() Dim search, found As Integer search = Console.ReadLine found = bsearch(search, 0, 4) Console.Write(found) Console.ReadKey() End Sub Function bsearch(ByVal num As Integer, ByVal low As Integer, ByVal high As Integer) Dim mid As Integer If high < low Then bsearch = -1 Else mid = (high + low) / 2 If x(mid) = num Then bsearch = mid Else If x(mid) > num Then high = mid - 1 Else low = mid + 1 End If bsearch = bsearch(num, low, high) End If End If End Function End Module
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 okplaymayday 的頭像
    okplaymayday

    漫遊於歷史與現代之間

    okplaymayday 發表在 痞客邦 留言(0) 人氣()