Decision Mathematics 1 (Paper 3D or 4D), topic 1 (Algorithms and graph theory), spec point 1.1
What is an algorithm?
An algorithm is a finite set of precise instructions that solves a problem. It can be written as numbered steps in words, or as a flow chart (ovals for start and stop, rectangles for instructions, diamonds for yes/no decisions).
Tracing an algorithm
To follow an algorithm, keep a trace table with a column for each variable, and write a new row whenever a value changes. Record any output and the point where the algorithm stops.
Worked example 1: a trace
- Let and .
- Let be the remainder when is divided by .
- If , output and stop.
- Let and , then go back to step 2.
| 84 | 30 | 24 |
| 30 | 24 | 6 |
| 24 | 6 | 0 |
The output is 6, the highest common factor of 84 and 30.
Efficiency, size and order
- The size of a problem measures how big it is, for example the number of items to sort or the number of vertices in a network.
- The efficiency of an algorithm is about its run time, which is usually proportional to the number of operations.
- The order describes how the run time grows with the size : linear (), quadratic () or cubic ().
Some standard results: a bubble sort is quadratic in the worst case. Dijkstra's algorithm (in its table form) is quadratic. Floyd's algorithm is cubic, because it has three nested loops over the vertices.
Worked example 2: scaling run times
A quadratic algorithm sorts 100 items in 0.4 seconds. For 500 items, the size is multiplied by 5, so the time is multiplied by :
For a cubic algorithm, the factor would be .
Finding the order of an algorithm
Count the operations in terms of . For example, if the number of comparisons is , the highest power is , so the order is quadratic.
Common mistake: multiplying the time by the scale factor itself for a quadratic algorithm. If the size is multiplied by , the time is multiplied by for a quadratic order and for a cubic one.
Exam tip: in a trace, write every value, including the final one that makes the algorithm stop. State the output clearly, and say what the algorithm does if asked.
Check yourself
A cubic algorithm takes 2 s for . Estimate the time for .
s.
The number of operations is . What is the order?
Quadratic.
What does a diamond mean in a flow chart?
A decision (a question with yes/no answers).