-1

Binary Search Algorithmファイルから連絡先リスト (2D 配列) を並べ替え、 を使用して名前を検索するプログラムを VB で作成していstarting withますuser input。次に、見つかった名前と、残りの連絡先情報を表示します。問題は、 が1 つの名前Binary Search Algorithmだけを検索したことです。という名前をすべて見つける必要があります。start withuser input

これまでの私のコードは次のとおりです。

Dim found As Boolean = False
Dim search as String = txtInput.Text

Do
    middle = CInt((first + last) / 2) 'calcuate the middle position of the scope

    If contacts(middle, 1).ToLower.StartsWith(search) Then 'if the middle name starts with the search String
        found = True 'name was found
    ElseIf contacts(middle, 1).ToLower < search Then 'if the search name comes after the middle position's value
        first = middle + 1 'move the first position to be 1 below the middle
    ElseIf contacts(middle, 1).ToLower > search Then 'if the search name comes before the middle position's value
        last = middle - 1 'move the last position to be 1 above the middle
    End If

Loop Until first > last Or found = True 'loop until the name is not found or the name is found

If found = True Then
    For x = 0 To 4 'display the whole list of data for that name
        txtDisplay.Text += contacts(middle,x).padLeft(15)
    Loop 
End If
4

2 に答える 2

3

バイナリ検索は、「一致する値のリストのどこか」で終了します。一致する可能性のある値が複数あると予想される場合は、一致が得られなくなるまでその時点から逆方向 (A 方向) に作業し、再び前方向 (Z 方向) に作業する必要があります。これは、すべての部分一致を見つける方法です。それらが表示される順序を気にしない場合は、コードの最後の部分を次のように変更できます。

いくつかの境界チェックを含むように編集されました:

If found = True Then
    lb = 0
    ub = UBound(contacts)
    if middle > lb Then
      ii = middle
      While contacts(ii, 1).ToLower.StartsWith(search)
        ii = ii - 1
        if ii < lb Then Exit While
      End While
      firstContact = ii + 1
    Else
      firstContact = lb
    End If

    ii = middle + 1
    If middle <= ub Then
      ii = middle
      While contacts(ii, 1).ToLower.StartsWith(search)
        ii = ii + 1
        if ii > ub Then Exit While
      End While
      lastContact = ii - 1
    Else
      lastContact = ub
    End If

    numMatching = lastContact - firstContact + 1

    Dim matchingContacts(1,1)
    ReDim matchingContacts(1 To numMatching, 0 To 4)

    For ii = 1 To numMatching
      For jj = 0 To 4
        matchingContacts(ii, jj) = contacts(firstContact + ii - 1, jj).padLeft(15)
      Next jj
    Next ii

End If

これにより、一致する連絡先の範囲が検索され、それらの連絡先のみを含む新しい配列が作成されます。私はこれをテストしていないので、タイプミスを許してください (私は VB を書くことはあまりありません)。境界チェックを追加しました。それが今「完璧」であるという保証はありません...

于 2013-07-30T16:34:35.877 に答える