索引数超过索引数组vb的维数

时间:2018-06-22 08:36:26

标签: vb.net recursion binary-search

在调用函数的行的 sub main 中,出现了一个我不知道如何解决的错误:

  

索引数超过了索引数组的维数

Module Module1
    Sub main()
        Dim names() As String = {"heimdall", "hella", "loki", "thor", "tyr", "odin"} 'list in order
        Dim last As Integer = names.Length - 1
        Dim first As Integer = 0
        Dim player As String = "thor"

        search(names(), last, first, player)

    End Sub

    Function search(ByVal names() As String, ByVal last As Integer, ByVal first As Integer, ByVal player As String)
        Dim midpoint As Integer = (first + last) \ 2
        Dim found As Boolean = False

        While found = False
            If last < first Then
                Return -1
            End If

            If names(midpoint) > player Then
                Return search(names, last, first, midpoint)
                found = True
            Else
                Return midpoint
                found = True
            End If
        End While


        Return midpoint 'automatically does this when found = true

    End Function

End Module

1 个答案:

答案 0 :(得分:0)

将括号传递给names()方法时,请删除search末尾的括号。声明数组时只需要这些。

search(names, last, first, player)