Linear Search Code

Below is a VB.NET implementation of a linear search.  The array is originally declared as a dynamic array, at the form level, so that it can be resized at runtime.  The form’s load event gives the array a size to start with then initialises it with data.  In this implementation, the user types the target value that they are searching for into a textbox on the form.  If the item being searched for is not found, the user is invited to add it to the list.

Public Class Form1

    Dim stNames() As String
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        ReDim stNames(9)
        stNames(0) = "Stan"
        stNames(1) = "Oliver"
        stNames(2) = "Homer"
        stNames(3) = "Marge"
        stNames(4) = "Bart"
        stNames(5) = "Lisa"
        stNames(6) = "Maggie"
        stNames(7) = "Athos"
        stNames(8) = "Porthos"
        stNames(9) = "Aramis"
    End Sub
 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim bFound As Boolean
        Dim stFind As String
        stFind = Me.txtFind.Text
 
        For iCount As Integer = 0 To UBound(stNames)
            If stNames(iCount) = stFind Then
                bFound = True
                Exit For
            End If
        Next
 
        Dim iReply As Integer
        If bFound = True Then
            MsgBox("found " & stFind)
        Else
            iReply = MsgBox(stFind & " not found.  Do you want to add it to the array?", vbYesNo)
            If iReply = vbYes Then
                'add it to the array
                ReDim Preserve stNames(UBound(stNames) + 1)
                stNames(UBound(stNames)) = stFind
            End If
        End If
    End Sub
End Class