首页 > 代码库 > 二分查找 - vb.net

二分查找 - vb.net

Module Module1

    Sub Main()
        Dim array(999) As Integer
        Dim searchValue As Integer
        Dim valueIndex As Integer
        Dim rnd As New Random()

        For i As Integer = 0 To UBound(array)
            If (i = 0) Then
                array(i) = rnd.Next(10)
            Else
                array(i) = rnd.Next(array(i - 1), array(i - 1) + 10)
            End If
            Console.WriteLine("array(" & i & ")=" & array(i))
        Next i

        Console.WriteLine(vbCrLf & "请输入一个1~100之间的整数:")
        searchValue = http://www.mamicode.com/Console.ReadLine()

        valueIndex = Find(array, searchValue)
        If (valueIndex <> -1) Then
            Console.WriteLine("查找成功!元素位于索引(" & valueIndex & ")处")
        Else
            Console.WriteLine("查找失败!")
        End If

        Console.ReadKey()
    End Sub

    Function Find(ByVal array() As Integer, ByVal searchValue As Integer) As Integer
        Dim result As Boolean
        Dim valueIndex As Integer
        Dim startIndex, endIndex As Integer

        startIndex = 0
        endIndex = UBound(array)
        result = BinarySearch(array, searchValue, startIndex, endIndex, valueIndex)

        Return IIf(result, valueIndex, -1)
    End Function

    Function BinarySearch(ByVal array() As Integer, ByVal searchValue As Integer, ByRef startIndex As Integer, ByRef endIndex As Integer, ByRef valueIndex As Integer) As Boolean
        If (array Is Nothing Or array.Length = 0) Then
            Return False
        End If

        Dim midIndex As Integer
        midIndex = Math.Ceiling((startIndex + endIndex) / 2)
        If (array(midIndex) = searchValue) Then
            valueIndex = midIndex
            Return True
        End If

        If (array(midIndex) < searchValue) Then
            startIndex = midIndex + 1
            endIndex = endIndex
        Else
            startIndex = startIndex
            endIndex = midIndex - 1
        End If

        Return BinarySearch(array, searchValue, startIndex, endIndex, valueIndex)
    End Function
End Module

二分查找 - vb.net