Formal Contracts

The Hoare Triple {P} C {Q}: The Mathematical Contract

If precondition P holds before block C runs, then postcondition Q holds unfailingly when it finishes. This is the formal contract between a specification and its implementation.

P Precondition valores != null && length > 0 Awaiting test…
C Code block maximoActual = maximo(valores) Idle
Q Postcondition ∀x ∈ valores: x ≤ maximoActual Awaiting test…
Simulator: test the contract with different inputs maximo(valores) — finds the maximum of an array
Pick a case to run the contract.
Loop Verification

Loop Invariants: The State That Never Breaks

An invariant is a logical statement that holds before the loop starts, after every iteration, and when it ends, guaranteeing the postcondition. In maximo(), it states: valores[0..i-1] has been scanned and maximoActual is its maximum.

Invariant: valores[0..i-1] scanned, maximoActual = partial maximum
04
19
22
37
45
51
68
73
Processed (invariant holds) Active element Pending
i = 0 · maximoActual = —

Before starting: segment [0..-1] is empty, the invariant holds trivially.

Guaranteed Termination

Total Correctness and the Bound Function: V = n − i

Partial correctness guarantees that if the loop terminates, the answer is correct. Total correctness also requires it to terminate: a positive integer bound function that strictly decreases each iteration proves it.

n 8
i 0
V = n − i 8

V starts at n = 8. Each iteration reduces it by 1. While V stays positive, the loop may continue; it can never go negative.

Asymptotic Analysis

The Interactive Big-O Notation Chart

Big-O describes how running time scales as the input size N grows toward infinity, ignoring constants and lower-order terms to focus on the dominant factor.

10 100 1K 10K 100K 1M N (input size) →
O(1) · O(log N) O(N) · O(N log N) O(N²) O(2^N)
N = 10
O(1) 1
O(log N) 4
O(N) 10
O(N log N) 40
O(N²) 100
O(2^N) 1,024
Case Analysis

Best, Worst, and Average Case in a Linear Search

An algorithm does not have a single speed: linear search is O(1) in the best case if the value sits at the front, and O(N) in the worst case if it is absent. Unless stated otherwise, the worst case is usually reported.

Searching for value 12 in the array:

12
45
7
89
34
2
67
90
15