Published by Patrick Mutisya · 14 days ago
Explain at which stage in the construction of an algorithm it is appropriate to introduce a function, and why this improves the design.
A function should be introduced when any of the following conditions are met:
| Stage of Development | Action | Reason for Using a Function |
|---|---|---|
| Problem Analysis | Identify distinct operations (e.g., “calculate average”, “sort list”). | Creates a clear mapping from problem description to code modules. |
| Algorithm Design (pseudocode) | Replace repeated step sequences with a named sub‑algorithm. | Reduces pseudocode length and highlights logical structure. |
| Implementation | Write the function definition before the main routine. | Ensures the main routine reads like a high‑level plan. |
| Testing & Debugging | Test each function independently. | Isolates faults and speeds up verification. |
Consider an algorithm that must compute the median of several data sets. The steps “sort the list” and “pick the middle element” are repeated for each data set.
Without functions (pseudocode):
READ n
FOR i FROM 1 TO n
READ size
READ size numbers INTO list
// sort list
FOR j FROM 1 TO size-1
FOR k FROM j+1 TO size
IF list[j] > list[k] THEN SWAP list[j], list[k]
END FOR
END FOR
// pick median
IF size MOD 2 = 1 THEN
median ← list[(size+1)/2]
ELSE
median ← (list[size/2] + list[size/2 + 1]) / 2
END IF
OUTPUT median
END FOR
With functions (pseudocode):
FUNCTION sortAscending(list)
FOR j FROM 1 TO LENGTH(list)-1
FOR k FROM j+1 TO LENGTH(list)
IF list[j] > list[k] THEN SWAP list[j], list[k]
END FOR
END FOR
END FUNCTION
FUNCTION median(list)
CALL sortAscending(list)
SET n ← LENGTH(list)
IF n MOD 2 = 1 THEN
RETURN list[(n+1)/2]
ELSE
RETURN (list[n/2] + list[n/2 + 1]) / 2
END IF
END FUNCTION
READ sets
FOR i FROM 1 TO sets
READ size
READ size numbers INTO data
OUTPUT median(data)
END FOR
Notice how the main loop now reads like a high‑level description, while the details of sorting and median extraction are encapsulated in functions.
The benefit can be expressed as a reduction in algorithmic complexity of the main flow:
\$\$
\text{Complexity}{\text{main}} = O(k) \quad\text{vs.}\quad \text{Complexity}{\text{main+functions}} = O(k) + \sum{i=1}^{m} O(fi)
\$\$
where \$k\$ is the number of high‑level steps, \$m\$ the number of functions, and \$f_i\$ the internal complexity of each function. The overall asymptotic order remains unchanged, but readability improves from \$O(k)\$ to \$O(k + m)\$ in terms of cognitive load.