2011-10-16 53 views
-2
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與此遞歸算法發生,我知道爲什麼錯誤是造成的,但不知道如何解決它?Stackoverflow與VB 2010中的二進制搜索的問題

+0

請廣告BinarySearch_Surname的頭(),所以我們可以看到參數。但是你正在改變MidPoint的方式,似乎不是'中間'。 –

+2

使用Array.BinarySearch()或[作業]標籤。 –

回答

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) 
+0

對不起,這仍然不行,我還不知道爲什麼?你能再請看看嗎,謝謝。 – Gilly

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變成一個返回值的函數,這樣你就可以將這些消息框放在搜索代碼之外。