Linear Search - Dessert Example
Linear Search - Dessert Example
Linear search is a simple way to find a specific item in a list. It checks each item one by one from the
start until it finds the target or reaches the end.
Linear search using a simple example with a 1-dimensional static array containing some
delicious dessert names.
Index: 1 2 3 4 5
Step-by-step process:
5. **Stop searching.**
If you look for `"cheesecake"` and it's not in the array, you will check all items and reach the end without
finding it. In that case, the search concludes that the item is **not present**.
A simple pseudo code for performing a linear search on a 1D static array containing the given
dessert names – which will include steps from declaration, initialization, inputting values, and
then performing the linear search.
Declare desserts: Array[1:5] of String // Step 1: Declare an array to hold dessert names
desserts[0] = "chocolate brownie" // For simplicity, assume values are already assigned as shown
desserts[3] = "ice-cream"
desserts[4] = "tiramisu" // (Optional) Step 3: Input values into the array if not hardcoded
Input "Enter the dessert to search for: ", searchvalue // Step 4: Ask the user to input the dessert to search for
for i from 1 to 5 do
found_index = i
end if
end for
else
end if
Method A: Values input within a loop into the array
Declare desserts: Array[1:5] of String // Step 1: Declare an array to hold dessert names
For i = 1 to 5 do
endfor
// Step 3: Input values into the array if not assigned during initialisation
For I = 1 to 5 do
endfor
Input "Enter the dessert to search for: ", searchvalue // Step 4: Ask the user to input the dessert to search for
for i from 1 to 5 do
found_index = i
end if
end for
else
end if
Sub Main()
Dim desserts(1 To 5) As String ' Step 1: Declare an array to hold dessert names
Dim i As Integer
Dim foundIndex As Integer = -1 ' Initialize a variable to keep track of search result
Next
Console.Write("Enter the dessert name for position " & i & ": ")
desserts(i) = Console.ReadLine()
Next
Console.Write("Enter the dessert to search for: ") ' Step 4: Ask the user to input the dessert to search for
searchValue = Console.ReadLine()
For i = 1 To 5 ' Step 5: Loop through each element in the array to find searchValue
foundIndex = i
Console.WriteLine("Search Successful!")
End If
Next
If foundIndex <> -1 Then ' Step 7: Check if found and output the result
Else
End If
Console.WriteLine("Press any key to exit.") ' Wait for user input before closing
Console.ReadKey()
End Sub
End Module