A message comes in from the greenhouse team. "Did the water ever drop to 48 yesterday?"
Comet points at the cards. "Easy. I can see it right there."
Wren turns all six cards face down. "Beacon cannot see the whole row at once. It checks one card at a time."
Comet flips the first card. 62. Then the second. 58. Then the third. 54.
She flips the fourth and laughs. "48! Found it in four checks."
Nova hovers beside Comet. "Great discovery," she says. "Now, what if the reading was never there?"
Comet thinks for a moment. "Then I would have to check every card before I could say no."
A linear search, also called a sequential search, checks each element of a list in order.
It stops when it finds the value it wants, or when every element has been checked.
index ← 1
found ← false
REPEAT UNTIL (found OR index > 6)
{
IF (readings[index] = 48)
{
found ← true
}
ELSE
{
index ← index + 1
}
} This search uses last week's REPEAT UNTIL loop. It stops when found is true, or when index runs past the end.
The condition index is greater than 6 keeps the search from asking for an index out of range.
Developers look for repeated code that differs only a little. Then they swap in one segment that uses a list.
Here is Comet's old code, and the list version that replaces it.
Old code List version
DISPLAY(reading1) FOR EACH reading IN readings
DISPLAY(reading2) {
DISPLAY(reading3) DISPLAY(reading)
DISPLAY(reading4) }
DISPLAY(reading5)
DISPLAY(reading6) A list lets many related items be treated as one value. Giving a collection one name, without its details, is a data abstraction.
Data abstractions manage complexity. The program talks about readings, not about six separate boxes.
| Statement | True or false? |
|---|---|
| A linear search checks elements in order, one at a time. | ? |
| A linear search can say a value is missing after checking only the first element. | ? |
| The list version works for 24 readings without adding new lines. | ? |
| A data abstraction gives a collection of data one name. | ? |
Sharp thinking. Tomorrow is Impact Friday: what happens when many people add to one list?