0

I have error

Index was outside the bounds of the array.

I wanna implement algorithm interpolation search on vb.net.

This is my code:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim NameArray(6) As String
    Dim lo As Integer
    Dim hi As Integer
    Dim searchName As String
    Dim FoundIt As Boolean
    Dim middle As Integer
    Dim position As Integer

    NameArray(1) = TextBox1.Text
    NameArray(2) = TextBox2.Text
    NameArray(3) = TextBox3.Text
    NameArray(4) = TextBox4.Text
    NameArray(5) = TextBox5.Text
    NameArray(6) = TextBox6.Text
    searchName = TextBox7.Text
    lo = 1
    hi = NameArray.Length
    FoundIt = False

    'vb.net function to sort elements in an array alphabetically and write the back in the correct order
    Array.Sort(NameArray)
    TextBox1.Text = NameArray(1)
    TextBox2.Text = NameArray(2)
    TextBox3.Text = NameArray(3)
    TextBox4.Text = NameArray(4)
    TextBox5.Text = NameArray(5)
    TextBox6.Text = NameArray(6)

    Do
        middle = lo + ((CDbl(hi - lo) / (NameArray(hi) - NameArray(lo))) * (searchName - NameArray(lo)))
        If NameArray(middle) = searchName Then
            FoundIt = True
            position = middle
        Else
            If NameArray(middle) < searchName Then
                lo = middle + 1
            Else
                hi = middle - 1
            End If
        End If
    Loop While Not FoundIt And lo <= hi
    If FoundIt = True Then
        TextBox9.Text = "found at position" & CDbl(position)
    End If
End Sub
gile
  • 5,580
  • 1
  • 25
  • 31
asepz
  • 1
  • 1
  • Possible that your array is starting from zero instead of one??? – user1234433222 Aug 22 '17 at 12:15
  • 1
    The error is because of this line: `hi = NameArray.Length`. The length of your array is 7, but the upper bound is 6. Later you try `NameArray(hi)` which is outside the bounds of the array. Try this instead: `hi = NameArray.Length - 1` – Chris Dunaway Aug 22 '17 at 13:20
  • 1
    [Arrays in Visual Basic](https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/arrays/). Please read [ask] and take the [tour] – Ňɏssa Pøngjǣrdenlarp Aug 22 '17 at 14:26

0 Answers0