1

任务我需要使用自制算法进行二进制搜索。

现在该程序应该可以工作,但不幸的是事实并非如此,他比较了它,但问题是他对城市收费。如果未找到,则显示输出中的内容。

本练习的目的是将搜索值与邮政编码进行比较。邮政编码包含邮政编码和城市名称。

Module Module1

    Sub Main()
        '                           0       1          2       3            4       5         6       7         8       9     
        Dim zipcodes() As String = {"1000", "Brussel", "2000", "Antwerpen", "3000", "Leuven", "8000", "Brugge", "9000", "Gent"}
        'Dim zipcodesCount As Integer = 5
        '
        Dim searchValues() As String = {"0500", "1000", "2000", "3000", "4000", "8000", "9000", "9500"}
        ' 
        Dim searchValueIndex As Integer
        For searchValueIndex = 0 To 7
            Dim searchValue As String = searchValues(searchValueIndex)
            '
            Dim index As Integer
            Dim found As Boolean = False
            Dim allesDoorzocht As Boolean = False

            Dim uBound, lBound As Integer
            uBound = zipcodes.GetUpperBound(0) - 1
            lBound = zipcodes.GetLowerBound(0)


            Do Until found OrElse allesDoorzocht

                index = (lBound + uBound + 1 ) \ 2

                If (searchValue = zipcodes(index)) Then
                    found = True
                End If

                If uBound <= lBound Then
                    allesDoorzocht = True
                End If

                If Not (found OrElse allesDoorzocht) Then

                    If searchValue > zipcodes(index) Then
                        lBound = index + 1
                    Else
                        uBound = index - 1
                    End If

                End If

            Loop


            If found Then
                Console.WriteLine(searchValue & " is zipcode of " & zipcodes(index + 1))
                ' Of : Console.WriteLine(searchValue & " is zipcode of " & zipcodes(index + 1))
            Else
                Console.WriteLine(searchValue & " not found")
            End If
        Next
        '
        Console.ReadLine()
    End Sub
End Module
4

2 回答 2

1

创建城市对象

Public Class City
    Public Property ZipCode As String 
    Public Property Name As String 
End Class

并使用数组City代替

Dim citiy() As City = { _
    New City With { .ZipCode = "1000", .Name = "Brussel" }, _
    New City With { .ZipCode = "2000", .Name = "Antwerpen" }, _
    New City With { .ZipCode = "3000", .Name = "Leuven" }, _
    New City With { .ZipCode = "8000", .Name = "Brugge" }, _
    New City With { .ZipCode = "9000", .Name = "Gent" } _
}

现在您可以像这样访问邮政编码和名称

city(i).ZipCode
city(i).Name

并且对应的城市名称和邮政编码具有相同的索引。


注意我正在使用 VS 2010 引入的自动属性和对象初始化程序。您可能可以删除行继续符号 _。(我仍在使用 VS 2008,通常是 C#)

于 2012-11-17T22:07:10.380 回答
0

您正在搜索数组邮政编码,该数组邮政编码应该按您编写的二进制搜索的升序排列,但"1000"<="Brussel"<="2000"不是真的。您必须确保您的算法只考虑数组的偶数元素。你通过拆分完美地做到了这一点。但在未找到的情况下,您必须确保边界仍然指向偶数索引而不是城市名称。所以你必须做lBound=index+2or uBound=index-2

于 2012-11-17T21:43:38.193 回答