Pseudocode
In questa pagina 4
Pseudocode is a free-form description of an algorithm written for a human reader. It uses constructs from programming languages (for, while, return, ...) when they are clear and effective, and natural language when it simplifies the description, provided a program can be easily derived from it. It gives a clear, unambiguous structure, is not meant for execution, and requires rigour. A programmer later translates it into a real language. See Computational Problems, Algorithms and Models of ComputationA computational problem is a relation between instances and solutions, an algorithm is a finite procedure that computes one valid solution for each instance in a model of computation (RAM), and a data structure organises the data the algorithm works on.Computational Problems, Algorithms and Models of Computation → for the design process.
Mandatory structure
Every algorithm is written as:
Algorithm name(parameters)
Input: brief description of the input instance
Output: brief description of the solution returned
<description of the elementary steps>- The header (signature + input-output relation) must come before the operations.
- Since an algorithm computes a function with , the header only needs to state what and are.
- The body must make the sequence of elementary steps for any input easy to determine.
Constructs
| Construct | Notation |
|---|---|
| assignment | x ← value |
| array indexing | A[i] (also A[i,j] for matrices) |
| conditional | if (condition) then { ... } else { ... } (else optional) |
| counting loop | for v ← initial to/downto final do { ... } |
| iterator loop | foreach element of an iterator do { ... } |
| pre-test loop | while (condition) do { ... } |
| post-test loop | repeat { ... } until (condition) |
| return | return, optionally with a value or a set of values |
| call | invocation of an algorithm (also itself, if recursive) |
In the slides the assignment also appears as <-.
Conventions
- Give algorithms meaningful names.
- Do not translate programming constructs into another language (write
if ... then, not a translated equivalent). - Use natural language only when it helps the reader and does not hide the sequence of operations.
- In a
forloop the variable is incremented automatically: do not write it. Inwhileandrepeatloops the variables controlling progression must be updated explicitly. - Three kinds of variables:
- local: defined and initialised by the algorithm, they do not persist after it ends;
- global: assumed defined by the caller, they persist;
- input parameters: listed after the name, initial values given by the caller. They may be global variables that persist. This is more flexible than Java, where parameters are passed by value (they become local variables); in Java too, modifications to the objects a parameter references persist.
returnmust agree with the input-output relation in the header. If the algorithm has an effect on global variables instead of returning a value (e.g. sorting a sequence ), that effect is described in theOutputline.returnmay be omitted if nothing is returned and it would be the last operation.
Recursive algorithms
- The header is crucial: every recursive call must use the same name and the same number and type of parameters as the signature.
- A call must agree with the input-output relation, and the value it returns must be assigned to a variable, otherwise it is lost.
- The pseudocode describes a generic call: also state the initial call that solves a given instance.
- Always include a base case (highlight it): without it the algorithm may loop forever and is not correct.
Worked examples
Transpose (for version)
Idea: swap each with for ; diagonal untouched.
Algorithm Transpose(A)
Input: A matrix of integers n x n with elements aij such that 0 ≤ i,j < n
Output: matrix transpose B = A^T
for i ← 0 to n-2 do { // rows
for j ← i+1 to n-1 do { // columns
exchange aij with aji
}
}
return AReturning avoids initialising a new matrix and copying the diagonal. The exchange can be made explicit:
c ← A[i,j]
A[i,j] ← A[j,i]
A[j,i] ← cTranspose (while version)
Algorithm Transpose(A)
Input: A matrix of integers n x n with elements aij such that 0 ≤ i,j < n
Output: matrix transpose B = A^T
i ← 0; j ← 1;
while i < n-1 do {
exchange aij with aji
if j = n-1 then {
i ← i+1;
j ← i+1;
} else {
j ← j+1;
}
}
return AHere the loop variables are updated by hand: when reaches the last column, move to the next row and restart just after the diagonal.
arrayMax
Algorithm arrayMax(A)
Input: array A[0 ÷ n-1] of n ≥ 1 integers
Output: max integer in A
currMax ← A[0];
for i ← 1 to n-1 do {
if (currMax < A[i]) then currMax ← A[i];
}
return currMaxAnalysed in Analysis of Algorithms and Asymptotic NotationThe worst-case time complexity t_A(n) counts elementary RAM steps on the hardest instance of size n; since it is hard to compute exactly, it is bounded asymptotically with O, Omega, Theta and o, ignoring constants and lower-order terms.Analysis of Algorithms and Asymptotic Notation → (complexity) and Correctness and Loop InvariantsCorrectness means termination plus solving the problem; it is proved with basic proof techniques (example, counterexample, contradiction, induction) and, for loops, with an invariant shown to hold initially, to be preserved, and to imply the final state.Correctness and Loop Invariants → (correctness).
arrayFind
Algorithm arrayFind(x, A)
Input: element x, array A[0 ÷ n-1] of n elements
Output: index i ∈ [0, n) such that A[i] = x, if it exists, otherwise -1
i ← 0;
while i < n do
if (x = A[i]) then return i;
else i ← i + 1;
return -1Two possible exits: early return i, or natural end of the loop followed by return -1.
InsertionSort
Algorithm InsertionSort(S)
Input: sequence S[0 … n-1] of n comparable elements
Output: sequence S rearranged in non-decreasing order
for i ← 1 to n-1 do {
curr ← S[i]
j ← i-1
while ((j ≥ 0) AND (S[j] > curr)) do {
S[j+1] ← S[j]
j ← j-1
}
S[j+1] ← curr
}
return SmaxSegment1 (iterative)
Length of the longest contiguous segment of 1s in a bit sequence .
Algorithm maxSegment1
Input: sequence S of n bits
Output: length of the longest contiguous segment of 1s
max ← 0; curr ← 0;
for i ← 1 to n do
if S[i] = 1 then
curr ← curr + 1;
if curr > max then max ← curr;
else curr ← 0;
return maxpower (recursive)
Computes for , integer , using for even and for odd .
Algorithm power(x, n)
Input: x ∈ R and integer n ≥ 0
Output: x^n
if (n = 0) then return 1; // BASE CASE
if (n is odd) then
y ← power(x, (n-1)/2);
return x · y · y;
else
y ← power(x, n/2);
return y · yNote the recursive call matches the signature, its result is stored in y, and the base case is explicit. Its complexity is in Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →.
Versione ripasso
- Always use this structure:
Algorithm name(parameters)
Input: ...
Output: ...
<body>- Constructs:
←assignment,A[i],if (...) then {...} else {...},for v ← a to/downto b do,foreach,while (...) do,repeat {...} until (...),return, calls (also recursive). - Rules
- Meaningful names; do not translate constructs; natural language only when it helps.
for: variable incremented automatically, do not write it.while/repeat: update the control variables explicitly.- Variables: local (vanish), global (persist), input parameters (may persist, unlike Java by-value; Java object references still persist).
returnconsistent with the header; if the effect is on global data, say it inOutput.
- Recursive: same name and parameters as the header, assign the returned value (else it is lost), give the initial call, always have a base case.
- Examples: Transpose (
forwith swap of for ;whileversion with manual updates), arrayMax, arrayFind, InsertionSort, maxSegment1, power. - Typical mistakes: missing header or
Output; forgettingj ← j+1in awhile; recursive call whose result is discarded; no base case. - See also Computational Problems, Algorithms and Models of ComputationA computational problem is a relation between instances and solutions, an algorithm is a finite procedure that computes one valid solution for each instance in a model of computation (RAM), and a data structure organises the data the algorithm works on.Computational Problems, Algorithms and Models of Computation → and Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →.