Algorithmics study and revision notes
2026-08-22
Many optimisation problems have enormous state spaces, expensive objectives, or NP-hard worst cases. Exact optimisation may be unnecessary or impossible within the available time. A heuristic aims to return a useful solution under a resource budget, but it does not remove the need for precise modelling or evidence.
The right question is not simply “Did the method find a good answer?” Ask what “good” means, which guarantee applies, what budget was used, which baseline was beaten, and whether the result repeats on unseen instances.
After studying this note, you should be able to:
The sections move from the strongest claims to the most empirical ones: a proved approximation, exact A*, single-solution local search, population methods, and finally experimental evaluation. For every method, keep the representation, move generator, stopping budget, and guarantee visible; the biological metaphor is never the specification.
For a first pass, focus on the four method classes, problem specification, set cover, A*, local search, annealing, and evaluation. Then use that common vocabulary to compare tabu search, evolutionary search, DE, ACO, and PSO without treating their metaphors as explanations.
These labels should not be used interchangeably:
A method may also be complete, meaning it eventually finds a solution if one exists, without being an efficient optimiser. Stochastic local SAT methods are usually incomplete; systematic SAT solvers can be complete.
Specify at least:
Representation determines reachability and cost. A TSP tour stored as a permutation supports swaps, insertions, and reversals while remaining a tour. Independent bit flips do not preserve a permutation.
Constraints can be handled by a feasibility-preserving representation, repair, rejection, a penalty term, or a solver embedded inside the search. Each choice changes the landscape. State whether a larger objective is better; the algorithms below use minimisation unless noted.
For iterative methods, a useful first estimate is
Incremental evaluation can matter more than the name of the metaheuristic. In TSP, recomputing a whole tour costs , while the cost change of a 2-opt move depends on only four affected edges and can be computed in .
A greedy method makes the best-looking available irreversible choice. It is exact only when a proof such as an exchange or cut argument establishes that local choices compose into a global optimum. Otherwise it may still have an approximation guarantee.
In weighted set cover, a universe must be covered by sets in a family . Set has cost . The goal is a minimum-cost subfamily whose union is .
greedy_set_cover(U, family):
uncovered = U
answer = empty list
while uncovered is not empty:
if no T in family covers a new element: report infeasible
choose T in family minimising c(T) / |T intersect uncovered|
among sets that cover a new element
append T to answer
remove T's elements from uncovered
return answer
For unweighted set cover, every cost is one, so choose the set covering most currently uncovered elements.
Charge the cost of a selected set equally to the elements it covers for the first time. The algorithm’s total charge equals its total cost.
Fix an optimal solution, and assign every universe element to one set of that solution which covers it. Consider one optimal set of cost with elements assigned to it; sets with no assigned elements contribute nothing. When assigned elements remain uncovered, covers at least those elements, so its current ratio is at most .
Greedy’s chosen ratio, and hence the charge to each element newly covered in that step, is no larger. Ordering the assigned elements by when they are first covered bounds their total charge by
where . Summing over the sets in the fixed optimum counts every element’s charge once. Greedy therefore costs at most times optimum. This is a proved worst-case guarantee, not an empirical claim that greedy is usually optimal.
A* searches a finite state graph with nonnegative transition costs for a minimum-cost path. It orders the frontier by
where is the best known cost from the start and estimates remaining cost.
put start in a priority queue with priority h(start)
while the queue is not empty:
n = remove smallest f
if n is a goal: return its reconstructed path
for each successor y:
if g[n] + cost(n,y) improves g[y]:
update g[y], parent[y], and its queue priority
An admissible heuristic satisfies , where is the true remaining cost; therefore at every goal. A consistent heuristic also satisfies
for every transition. Test for a goal when it is removed from the priority queue, not merely when it is generated. With consistency, a standard closed-set graph search need not reopen expanded states. With admissibility but not consistency, reopening improved states preserves optimality. The graph note gives the correctness argument in full.
Heuristic quality affects work, not the optimum: gives Dijkstra; a more informative admissible heuristic can expand fewer states. If everywhere and both are admissible, dominates .
The travelling salesperson problem (TSP) asks for a minimum-weight Hamiltonian cycle: visit every city exactly once and return to the start. A symmetric -city instance has distinct tours after ignoring start rotation and reversal, so exhaustive enumeration grows too quickly.
Nearest neighbour starts at a city and repeatedly visits the closest unvisited city, finally returning to the start. A straightforward implementation is . It is a useful baseline and can be poor because an attractive early edge can force an expensive final connection. Try every start before crediting the method itself with one lucky start.
A common local move is 2-opt. Choose two nonadjacent tour edges and , remove them, reverse the intervening segment, and add and . For a symmetric TSP, its cost change is
A negative improves a minimisation tour. Repeating improving 2-opt moves reaches a 2-opt local optimum, not necessarily the global optimum.
Local search keeps one or a few complete candidates and moves through a neighbourhood:
local_search(x):
repeat:
choose an improving neighbour y of x
if no improving neighbour exists: return x
x = y
Best improvement scans the whole neighbourhood and takes the largest gain. First improvement takes the first gain found and may perform many cheaper iterations. The result depends on neighbourhood, scan order, tie policy, and initial state.
Plateaus contain equal-valued neighbours; ridges require coordinated moves; local optima have no improving neighbour. Random restarts sample different attraction basins. Allowing sideways or worsening moves can escape a basin but introduces new control parameters.
For minimisation, propose a random neighbour and set
Accept every move with . Accept a worsening move with probability
where temperature decreases over time.
x = initial candidate
best = x
for t = 1, 2, ... until budget ends:
T = schedule(t)
y = random neighbour of x
delta = cost(y) - cost(x)
if delta <= 0 or random(0,1) < exp(-delta/T):
x = y
if cost(x) < cost(best): best = x
return best
High temperature explores; low temperature becomes nearly greedy. A scale that is hot for one objective may be frozen for another, so inspect typical move deltas when choosing the initial temperature. Extremely slow theoretical cooling can guarantee asymptotic convergence under restrictive conditions but is rarely practical. Finite-budget performance depends on proposal moves, schedule, reheating/restarts, and stopping.
Tabu search commonly chooses the best available neighbour even when it is worse, while short-term memory prevents immediate cycles. Rather than storing every complete solution, it records move attributes such as “edge was removed” for a fixed tabu tenure.
An aspiration rule overrides tabu status when a move produces a new global best. Tenure that is too short permits cycling; tenure that is too long excludes useful regions. Long-term frequency memory can encourage rarely used components or diversify after stagnation.
For a Boolean formula in conjunctive normal form, a complete assignment is a state. A one-flip neighbourhood changes one variable, and an objective may count unsatisfied clauses.
A WalkSAT-style step selects an unsatisfied clause, then either flips a random variable in it or flips a variable with a favourable break/make score. Noise helps cross local minima. Restarts reduce dependence on one assignment.
This is incomplete stochastic local search: failure within a budget does not prove unsatisfiability. Complete DPLL/CDCL solvers add systematic branching, propagation, conflict analysis, learned clauses, and backtracking.
An evolutionary algorithm maintains a population:
Representation-specific operators are essential. One-point crossover on bit strings preserves length, but naïvely crossing two TSP permutations can duplicate cities. Order-based crossover and swap/inversion mutation preserve permutation structure.
Selection pressure that is too weak makes progress slow; too strong destroys diversity and can converge prematurely. Population size, mutation scale, survivor policy, and constraint handling are part of the algorithm and must be reported.
Differential evolution (DE) is designed for vectors . In the common DE/rand/1/bin variant, for each target vector :
choose distinct population indices , all different from ; thus this variant needs at least four population members;
create a donor
choose one forced coordinate and create the trial vector coordinatewise:
repair, reflect, clip, or resample coordinates outside their bounds; and
record for the next generation if it is no worse than ; otherwise retain .
controls differential step scale, controls coordinate mixing, and population size controls diversity and evaluations per generation. Donors are normally drawn from the unchanged current generation and replacements installed together, avoiding iteration-order effects. One generation evaluates roughly one trial per population member. Compare methods by total objective evaluations when objective cost dominates.
For polynomial fitting, a candidate vector contains coefficients. RMSE strongly penalises large residuals and is sensitive to outliers. A median absolute or squared residual is robust to a minority of extreme points but may ignore broad moderate error. Report the precise loss and data scale.
If linear, quadratic, and cubic models are all allowed, fitting error alone tends to prefer extra flexibility. Penalise complexity, validate on held-out data, or search degree separately. Optimising coefficients and claiming the true degree has been recovered are different tasks.
These are useful survey methods; their equations matter more than their biological metaphors.
In ant colony optimisation (ACO), a construction step chooses component with probability proportional to
where is learned pheromone and is problem-specific desirability. More precisely, if is the set of feasible next components from partial solution , initialise pheromones positively and sample
with probability zero outside , where and the denominator must be positive. If is empty before a solution is complete, the construction needs a stated repair, backtracking, or rejection policy. After constructing and evaluating complete solutions, evaporate and deposit nonnegative, quality-dependent amounts:
Evaporation discounts old evidence; reinforcement favours components of selected good solutions. Without positive lower bounds or another exploration rule, pheromones can become so unequal that the search effectively locks in early choices.
In particle swarm optimisation (PSO), particle has position , velocity , personal best , and a neighbourhood or global best :
Initially set and choose each particle’s from the initial personal bests according to the communication topology. Here and are normally independent vectors whose coordinates are sampled uniformly from . After moving and applying the boundary rule, evaluate the new position, replace if is better, and update the relevant neighbourhood best .
One synchronous iteration uses about one objective evaluation per particle. Inertia , attraction coefficients, velocity control, boundary rules, and the communication topology all affect convergence and diversity; omitting any of these choices leaves the algorithm underspecified.
Suppose tour has edge costs , total 30. Replace edges and by of cost 3 and of cost 4. Reversing the middle segment gives
with cost . The 2-opt delta is , so every improving local-search rule accepts it.
Later, suppose a proposed move is worse by . At temperature , annealing accepts it with probability
At , the probability is . The same move changes from plausible exploration to almost certain rejection as the search cools.
Stochastic optimisation needs repeated independent runs. Report:
Use paired instances and, where meaningful, paired random scenarios when comparing methods. Do not tune on the same instances used for final claims. The best run answers “Was this ever achieved?”; it does not estimate typical performance.
| Method | Guarantee | Typical work unit | Main risk |
|---|---|---|---|
| Greedy set cover | approximation | scan coverage gains | irreversible early choices |
| A* | optimal under stated heuristic/search conditions | priority-queue expansion | exponential time and memory |
| Nearest-neighbour TSP | heuristic baseline | choose next city | expensive closing edge |
| 2-opt local search | local optimum | edge-pair delta | trapped basin |
| Simulated annealing | no practical finite-budget guarantee | one sampled neighbour | schedule mismatch |
| Tabu search | heuristic | candidate neighbourhood plus memory | tenure/attribute design |
| Stochastic SAT | incomplete heuristic | one variable flip plus clause updates | cannot certify unsatisfiability |
| Evolutionary search | heuristic | population generation | lost diversity |
| DE | heuristic | one trial per target vector | scale and boundary handling |
| ACO | heuristic | constructed population plus pheromone update | stagnation and construction policy |
| PSO | heuristic | one move and evaluation per particle | premature convergence and boundary handling |
differential_evolution
implements several DE strategies, bounds, constraints, parallel
evaluation, and optional polishing. It is stochastic and often uses many
more objective evaluations than a gradient method, so fix the random
generator and count evaluations.pathfinding crate
implements A, BFS, Dijkstra, flow, and related searches over
caller-supplied successor functions. Correct A optimality still
depends on nonnegative costs and an appropriate heuristic; the library
cannot infer those semantic conditions.