An algorithm is designed to search a database of astronomical objects, where their distances in Megaparsecs (Mpc) are stored in an ascendingly sorted list, galactic_distances, for a specific distance target_distance.
idx = 0
is_located = False
exceeded = False
while (idx < len(galactic_distances)) and (not is_located) and (not exceeded):
if galactic_distances[idx] == target_distance:
is_located = True
elif galactic_distances[idx] > target_distance:
exceeded = True
else:
idx = idx + 1
The boolean variable is_located helps make the algorithm efficient by terminating the search as soon as the target is found.
Describe how the use of the exceeded variable also helps to make the algorithm efficient.
159 exam-style questions on Edexcel GCSE Computer Science Algorithms, covering Constructs for solving problems, Variables, constants and data structures, Arithmetic, relational and logical operators, Tracing algorithm output with trace tables, Types of error and correcting logic errors, Standard algorithms (sorts and searches), and Evaluating algorithm fitness and efficiency. Each one has a worked solution and a mark scheme showing where the marks go.