Reputation: 31
task I need a binary search with a homemade algorithm.
Now the program should work, but unfortunately this is not the case, he compares it but problem is he charging cities. than those in the output if not found is displayed.
The purpose of this exercise is that the search values are compared with the zipcodes. zipcodes contain so a postal code and the name of the city.
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
Upvotes: 1
Views: 995
Reputation: 112324
Create City objects
Public Class City
Public Property ZipCode As String
Public Property Name As String
End Class
and work with arrays of City
instead
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" } _
}
Now you can access zip codes and names like this
city(i).ZipCode
city(i).Name
and corresponding city names and zip codes have the same index.
Note I am using automatic properties and object initializers that have been introduced with VS 2010. You can probably drop the line continuation signs _. (I am still working with VS 2008 and usually C#)
Upvotes: 1
Reputation: 1923
You are searching the array zipcodes which should be in ascending order for the binary search you wrote, but "1000"<="Brussel"<="2000"
is not true. You have to make sure that your algorithm only regards the even elements of your array. You did that perfectly by splitting. But in the not found case, you have to make sure that bounds are still pointing to even indices and not the city names. So you have to do lBound=index+2
or uBound=index-2
.
Upvotes: 0