Salta al contenuto
Note per Studenti Pseudocode Report

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 i→si \to s with (i,s)∈Π(i, s) \in \Pi, the header only needs to state what ii and ss 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 for loop the variable is incremented automatically: do not write it. In while and repeat loops 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.
  • return must 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 SS), that effect is described in the Output line.
  • return may 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.

See 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 →.

Worked examples

Transpose (for version)

Idea: swap each aija_{ij} with ajia_{ji} for i<ji < j; 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 A

Returning AA 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] ← c

Transpose (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 A

Here the loop variables are updated by hand: when jj reaches the last column, move to the next row and restart jj 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 currMax

Analysed 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 -1

Two 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 S

maxSegment1 (iterative)

Length of the longest contiguous segment of 1s in a bit sequence S[1],…,S[n]S[1], \dots, S[n].

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 max

power (recursive)

Computes xnx^n for x∈Rx \in \mathbb{R}, integer n≥0n \ge 0, using xn=(xn/2)2x^n = (x^{n/2})^2 for even nn and xn=x⋅(x(n−1)/2)2x^n = x \cdot (x^{(n-1)/2})^2 for odd nn.

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 · y

Note 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>

Teoria collegata