在VB 2010中使用BinarySearch的Stackoverflow问题

时间:2011-10-16 11:45:24

标签: database vb.net algorithm recursion stack-overflow

Public Sub BinarySearch_Surname(ByVal BrownieArray() As Brownie_Structure, ByVal SearchItem As String, ByVal LowInt As Integer, ByVal HighInt As Integer)
    Dim ItemFound As Boolean = False
    Dim SearchFailed As Boolean = False
    Dim Midpoint As Integer = Int((LowInt + HighInt) / 2)

    Try
        If BrownieArray(Midpoint).Surname = SearchItem Then
            ItemFound = True
        Else
            If LowInt >= HighInt Then
                SearchFailed = True
            Else
                If BrownieArray(Midpoint).Surname < SearchItem Then
                    **BinarySearch_Surname(BrownieArray, Midpoint + 1, HighInt, ItemFound)
                Else
                    BinarySearch_Surname(BrownieArray, LowInt, Midpoint - 1, HighInt)**
                End If
            End If
        End If
        If SearchFailed = True Then
            MessageBox.Show("Failed to find Suranme in database", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If
        If ItemFound = True Then
            MessageBox.Show("Surname: " & BrownieArray(Midpoint).Surname, "Found", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Sub
        End If
    Catch
        MessageBox.Show("Failed to find , please insert correct infomation and try again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        Exit Sub
    End Try
End Sub

使用这种递归算法发生StackOverflow,我知道为什么会导致错误,但不知道如何解决它?

2 个答案:

答案 0 :(得分:1)

这一行:

If LowInt >= HighInt Then

应该是:

If LowInt > HighInt Then

这一行:

BinarySearch_Surname(BrownieArray, Midpoint + 1, HighInt, ItemFound)

应该是:

BinarySearch_Surname(BrownieArray, SearchItem, Midpoint + 1, HighInt)

这一行:

BinarySearch_Surname(BrownieArray, LowInt, Midpoint - 1, HighInt)

应该是:

BinarySearch_Surname(BrownieArray, SearchItem, LowInt, Midpoint - 1)

答案 1 :(得分:0)

您将错误的参数传递给递归调用,它应该是这样的:

  If BrownieArray(Midpoint).Surname < SearchItem Then
      BinarySearch_Surname(BrownieArray, SearchItem, Midpoint + 1, HighInt)
  Else
      BinarySearch_Surname(BrownieArray, SearchItem, LowInt, Midpoint - 1)                
  End If

你的递归退出条件也是错误的,它应该是:

  If LowInt > HighInt Then // > instead of >=

此外,您可以将SUB转换为返回值的函数,以便将这些消息框保留在搜索代码之外。