Linear Search
Finds a name in a list, ignoring upper and lower case.
- Level
- Intermediate
- Topic:
- Arrays
- Concepts:
- Input & output
- Arrays
- Mientras
- Text
Run, change and debug this example in your browser.
What you'll learn
A Mientras loop walks the array and stops as soon as it finds the name. Mayusculas converts both texts so they compare equal however they were typed.
Code
Algoritmo BusquedaLineal Definir nombres, buscado Como Caracter Definir i, posicion Como Entero Dimension nombres[6] nombres[1] <- "Ana" nombres[2] <- "Bruno" nombres[3] <- "Carla" nombres[4] <- "Diego" nombres[5] <- "Luis" nombres[6] <- "Sofía" Escribir "¿A quién buscas?" Leer buscado posicion <- 0 i <- 1 // Se detiene en cuanto lo encuentra Mientras i <= 6 Y posicion = 0 Hacer Si Mayusculas(nombres[i]) = Mayusculas(buscado) Entonces posicion <- i FinSi i <- i + 1 FinMientras Si posicion > 0 Entonces Escribir nombres[posicion], " está en la posición ", posicion, "." SiNo Escribir buscado, " no está en la lista." FinSiFinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
¿A quién buscas?User answer: luisLuis está en la posición 5.
Complexity
How much work and memory it needs as the amount of data (n) grows.
| Case | Cost |
|---|---|
| Best | O(1) |
| Average | O(n) |
| Worst | O(n) |
| Memory | O(1) |
Challenge
If the name isn't there, offer to add it to the end of the list.
Show hint
You'll need a bigger array from Dimension and a variable counting how many names are stored.
Related examples
Roman Numerals
Converts a number from 1 to 3999 into Roman numerals.
AdvancedHangman
Guess a secret word letter by letter, with six mistakes allowed.
AdvancedShopping List
Adds items to a list that grows until you type FIN.
Advanced