Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A shop stores the colours of the ten bicycles in its window in an array Colours: red, blue, red, green, white, red, blue, black, red, grey. A linear search that stops at the first match is not enough: the manager wants to know how many bicycles have a given colour.
Write a pseudocode algorithm that inputs a colour, looks at every item of the array, and outputs how many items match. How many does it output for red?
Linear search: compare each item in turn from the first; stop when it is found or the list ends. Bubble sort: compare each pair of neighbours and swap them if they are in the wrong order; repeat passes until a pass makes no swaps. A pass over items makes comparisons at most.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
A model answer.
DECLARE Colours : ARRAY[1:10] OF STRING
INPUT Wanted
Matches ← 0
FOR Index ← 1 TO 10
IF Colours[Index] = Wanted
THEN
Matches ← Matches + 1
ENDIF
NEXT Index
OUTPUT MatchesThe run. Red is at the indexes , , and , so the output is .
Answer: .
Watch out. A WHILE loop with a Found flag would stop at index . Here every item must be checked, so a FOR loop is the right choice.
Log in to join the discussion.
Loading…