Algorithms, Clustering and Neural Networks in Numbers: Sorting Operation Counts, Graph Traversal, Shortest Paths and Spanning Trees, Hierarchical Linkages and a Feed-Forward Pass

Section 4 of the Data Science and AI paper names an introduction to graph theory, basic sorting algorithms (bubble, selection) and traversals, and Section 6 names hierarchical clustering (single, complete and average linkage, top-down and bottom-up) and the feed-forward neural network; the first chapters give the ideas without a worked case. Bubble sort on 5, 1, 4, 2, 8 takes 9 comparisons and 4 swaps (equal to its 4 inversions) where selection sort takes 10 comparisons and 2 swaps; a weighted graph with five vertices has a minimum spanning tree of weight 10 and shortest path A to E of length 10; hierarchical clustering of the points 1, 2, 6, 7, 15 joins the last point at height 8, 14 or 11 under single, complete or average linkage; and a two-layer network with ReLU and sigmoid maps the input (1, 2) to 0.3475.
Overview

Basic Sorting Algorithms: Counting Comparisons and Swaps

1 min read

A sorting algorithm is judged by comparisons and by moves. Bubble sort repeatedly swaps adjacent out-of-order pairs and stops after a pass with no swap. On 5, 1, 4, 2, 8 it does 3 passes, 9 comparisons and 4 swaps; the number of swaps always equals the number of inversions (pairs i < j with aᵢ > aⱼ), here 4. Its worst case is n(n − 1)/2 comparisons and swaps (a reversed array), its best case n − 1 comparisons (sorted input, with the early-exit test), and it is stable. Selection sort finds the minimum of the unsorted part and swaps it into place: always n(n − 1)/2 = 10 comparisons for n = 5 whatever the input, but at most n − 1 swaps (2 here), which is why it suits expensive writes; it is not stable. Insertion sort shifts larger elements right and inserts: 7 comparisons and 4 shifts here (shifts = inversions again), best case n − 1 and worst n(n − 1)/2, and it is the fastest of the three on nearly sorted data. All three are Θ(n²) in the worst case; merge sort is Θ(n log n) with n log₂ n ≈ 9,966 comparisons for n = 1000, against quicksort's worst case of n(n − 1)/2 = 499,500 (rare with a good pivot, average about 1.39 n log₂ n). The comparison-sorting lower bound is ⌈log₂ n!⌉, about n log₂ n.

Algorithm (5, 1, 4, 2, 8)ComparisonsSwaps or shifts
Bubble94
Selection102
Insertion74
Inversions in the input—4

A sorting algorithm is judged by comparisons and by moves. Bubble sort repeatedly swaps adjacent out-of-order pairs and stops after a pass with no swap. On 5, 1, 4, 2, 8 it does 3 passes, 9…

Graph Theory: Traversal, Shortest Paths and Spanning Trees

1 min read

A graph G = (V, E) with |V| = n has at most n(n − 1)/2 edges (10 for n = 5) if undirected and simple, and a connected graph needs at least n − 1; a tree has exactly n − 1. The sum of degrees is 2|E|. An adjacency matrix costs Θ(n²) memory and answers 'is there an edge?' in O(1); an adjacency list costs Θ(n + |E|) and is better for sparse graphs. Take edges A–B 4, A–C 2, B–C 1, B–D 5, C–D 8, C–E 10, D–E 2. Breadth-first search from A (queue, visiting neighbours alphabetically) gives A B C D E, layer by layer, and finds fewest-edge paths in O(n + |E|); depth-first search (stack or recursion) gives A B C D E here and detects cycles and orders vertices by finishing time (topological order for a DAG). Dijkstra's algorithm (non-negative weights, priority queue, O((n + |E|) log n)) gives shortest distances from A: B = 3 (via C), C = 2, D = 8 (A–C–B–D), E = 10 (A–C–B–D–E: 2 + 1 + 5 + 2) — not the direct C–E edge of 10 — while Bellman–Ford handles negative weights. Kruskal's algorithm sorts the edges and adds each that joins two components (union–find): B–C 1, A–C 2, D–E 2, B–D 5; the minimum spanning tree has n − 1 = 4 edges and weight 10. A spanning tree is unique only when edge weights are distinct.

AlgorithmResult on the example graphCost
BFS from AA B C D EO(n + |E|)
DFS from AA B C D EO(n + |E|)
Dijkstra, A to E10O((n + |E|) log n)
Kruskal MSTweight 10O(|E| log |E|)

A graph G = (V, E) with |V| = n has at most n(n − 1)/2 edges (10 for n = 5) if undirected and simple, and a connected graph needs at least n − 1; a tree has exactly n − 1. The sum of…

Hierarchical Clustering: Single, Complete and Average Linkage

1 min read · 2 parts

Agglomerative (bottom-up) clustering starts with every point as its own cluster and repeatedly merges the two closest clusters, recording the merge distance in a dendrogram; divisive (top-down) clustering starts with one cluster and splits recursively. The cluster distance is the linkage: single = the minimum pairwise distance (can chain), complete = the maximum (compact clusters), average = the mean of all pairwise distances. For the one-dimensional points 1, 2, 6, 7, 15 the first merges are always (1, 2) and (6, 7) at height 1. The next merge, of {1, 2} and {6, 7}, happens at 4 under single linkage (nearest pair 2 and 6), 6 under complete (farthest pair 1 and 7) and 5 under average ((5 + 6 + 4 + 5)/4). The last point 15 joins at 8 (single: 15 − 7), 14 (complete: 15 − 1) and 11 (average: (14 + 13 + 9 + 8)/4), so the heights differ although the tree order is the same. Cutting the dendrogram at a chosen height gives a flat clustering: with single linkage a cut at 5 leaves {1, 2, 6, 7} and {15}. The naive algorithm costs O(n³) time and O(n²) memory (a distance matrix), which is why it does not scale like k-means; and Ward's method (minimum increase in within-cluster variance) is another common linkage.

LinkageMerge {1,2} with {6,7}Add 15
Single48
Complete614
Average511
Agglomerative vs divisive
Agglomerative (bottom-up)
  • Starts: every point its own cluster
  • Repeatedly merges the two closest
Divisive (top-down)
  • Starts: one cluster
  • Splits recursively
Merge distances are recorded in a dendrogram.

Agglomerative (bottom-up) clustering starts with every point as its own cluster and repeatedly merges the two closest clusters, recording the merge distance in a dendrogram; divisive…

The Feed-Forward Neural Network: a Forward Pass and One Gradient

2 min read · 1 part

A feed-forward network passes the input through layers of weighted sums and non-linear activations, with no cycles. Take two inputs x = (1, 2), a hidden layer of two ReLU units with W₁ = [[0.5, −0.3], [0.2, 0.8]] and b₁ = (0, −0.1), and one sigmoid output with w₂ = (0.6, −0.4), b₂ = 0.05. The hidden pre-activation is z₁ = W₁x + b₁ = (0.5 − 0.6 + 0, 0.2 + 1.6 − 0.1) = (-0.1, 1.7); ReLU = max(0, z) gives a₁ = (0.0, 1.7) (the first unit is inactive for this input). The output pre-activation is z₂ = w₂·a₁ + b₂ = 0 − 0.68 + 0.05 = -0.63, and the sigmoid σ(z) = 1/(1 + e⁻ᶻ) gives ŷ = 0.3475. With target y = 1 the cross-entropy loss is −ln ŷ = 1.0570, and for a sigmoid output with cross-entropy the gradient at the output pre-activation is simply ŷ − y = -0.6525; the backpropagation chain rule gives ∂L/∂w₂ = (ŷ − y)a₁ = (-0.00, -1.1092), and the gradient passes back to the hidden layer only through the active ReLU unit (derivative 1 for z > 0, 0 otherwise). Without a non-linear activation the layers would collapse to one linear map; with enough hidden ReLU units the network can approximate any continuous function (universal approximation). Parameters: the weights here number 4 + 2 + 2 + 1 = 9 (two biases in layer 1, one in layer 2).

QuantityCalculationValue
Hidden pre-activationW₁x + b₁(-0.1, 1.7)
After ReLUmax(0, z)(0.0, 1.7)
Output ŷσ(w₂·a₁ + b₂)0.3475
Cross-entropy loss−ln ŷ1.0570
🎯 Counts and one neuron, computed
Bubble sort and insertion sort make n(n − 1)/2 comparisons in the worst case, 45 for n = 10, and selection sort makes at most n − 1 swaps. Merge sort makes about n log₂ n, 33 for n = 10. In single-linkage clustering the distance between clusters is the minimum pairwise distance, in complete linkage the maximum. A neuron with inputs (1, 2), weights (0.5, −0.25) and bias 0.1 has z = 0.5 − 0.5 + 0.1 = 0.1, so ReLU gives 0.1 and the sigmoid 1/(1 + e^(−0.1)) = 0.525.

A feed-forward network passes the input through layers of weighted sums and non-linear activations, with no cycles. Take two inputs x = (1, 2), a hidden layer of two ReLU units with W₁ =…

Key takeaways

  • Bubble-sort swaps and insertion-sort shifts equal the number of inversions; selection sort always does n(n − 1)/2 comparisons but at most n − 1 swaps; all three are Θ(n²).
  • A simple graph has at most n(n − 1)/2 edges and a tree exactly n − 1; BFS finds fewest-edge paths, Dijkstra shortest weighted paths, Kruskal a minimum spanning tree.
  • Single linkage uses the nearest pair (chaining), complete the farthest, average the mean of all pairs; the dendrogram height is the merge distance.
  • A forward pass is z = Wx + b then an activation; for sigmoid output with cross-entropy the output gradient is ŷ − y; ReLU units pass gradient only when active.
  • Without a non-linear activation, stacked layers collapse into a single linear map.

Practice questions (24)

Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.

  1. Bubble sort (with early exit) is run on the array 5, 1, 4, 2, 8. The total number of swaps performed is:

    Numerical answer — type the value.

    Show answer

    Answer: 4

    The swaps equal the inversions: (5,1), (5,4), (5,2), (4,2) = 4. The comparisons are 4 + 3 + 2 = 9 over three passes; the third pass makes no swap, so the early-exit test stops the sort.
  2. Selection sort on any array of 5 distinct elements performs how many comparisons?

    Numerical answer — type the value.

    Show answer

    Answer: 10

    It always does (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 = 10 comparisons, independent of the input order; this is why it has no best case better than the worst.
  3. Which sorting algorithm performs the fewest element swaps in the worst case, at most n − 1?

    1. Selection sort
    2. Quicksort
    3. Insertion sort (as shifts)
    4. Bubble sort
    Show answer

    Answer: A — Selection sort

    Selection sort places each element with one swap, so at most n − 1; bubble and insertion sort perform up to n(n − 1)/2 swaps or shifts on reversed data.
Show the other 21 questions
  1. A simple undirected graph on 5 vertices can have at most how many edges?

    Numerical answer — type the value.

    Show answer

    Answer: 10

    n(n − 1)/2 = 5 × 4/2 = 10, the complete graph K₅. A tree on 5 vertices has exactly 4.
  2. In the graph with edges A–B 4, A–C 2, B–C 1, B–D 5, C–D 8, C–E 10, D–E 2, the shortest distance from A to E (Dijkstra) is:

    Numerical answer — type the value.

    Show answer

    Answer: 10

    A–C (2) → B (3) → D (8) → E (10): 2 + 1 + 5 + 2 = 10, against 12 for the shorter-looking route A–C–E (2 + 10), so the path with more edges is shorter.
  3. The minimum spanning tree weight of the same graph (Kruskal) is:

    Numerical answer — type the value.

    Show answer

    Answer: 10

    Sorted edges: B–C 1, A–C 2, D–E 2, A–B 4 (cycle, rejected), B–D 5 (joins the two components). The tree is 1 + 2 + 2 + 5 = 10 with n − 1 = 4 edges.
  4. For the points 1, 2, 6, 7, 15 under complete linkage, the height at which the last point 15 joins the cluster {1, 2, 6, 7} is:

    Numerical answer — type the value.

    Show answer

    Answer: 14

    Complete linkage uses the maximum pairwise distance: 15 − 1 = 14. Single linkage would give 8 (15 − 7) and average 11.
  5. Which linkage is most prone to the "chaining" effect that merges elongated chains of points into one cluster?

    1. Complete linkage
    2. Average linkage
    3. Ward's method
    4. Single linkage
    Show answer

    Answer: D — Single linkage

    Single linkage merges clusters whenever any two points are close, so a line of points links up through nearest neighbours; complete linkage requires all pairs to be close and gives compact clusters.
  6. For the network in the chapter (x = (1, 2), ReLU hidden layer giving (0, 1.7), w₂ = (0.6, −0.4), b₂ = 0.05) the output pre-activation z₂ (two decimals) is:

    Numerical answer — type the value.

    Show answer

    Answer: -0.63

    z₂ = 0.6 × 0 + (−0.4) × 1.7 + 0.05 = −0.63. The inactive ReLU unit contributes nothing, and the sigmoid of −0.63 is 0.3475.
  7. For a sigmoid output ŷ = 0.3475 and target y = 1 with cross-entropy loss, the gradient of the loss with respect to the output pre-activation z₂ (four decimals) is:

    Numerical answer — type the value.

    Show answer

    Answer: -0.6525

    For sigmoid with cross-entropy, ∂L/∂z = ŷ − y = 0.3475 − 1 = −0.6525: the negative sign says to increase z₂ to raise the predicted probability.
  8. Which statements are correct?

    1. Insertion sort runs in about n − 1 comparisons on an already sorted array
    2. A neural network of linear activations is equivalent to a single linear map
    3. Dijkstra's algorithm needs non-negative edge weights
    4. Complete linkage always gives the same dendrogram heights as single linkage
    Show answer

    Answer: A — Insertion sort runs in about n − 1 comparisons on an already sorted array; B — A neural network of linear activations is equivalent to a single linear map; C — Dijkstra's algorithm needs non-negative edge weights

    The heights differ (1, 1, 4, 8 against 1, 1, 6, 14 here); the first three statements are standard.
  9. Bubble sort without the early-exit check is run on 6 elements. The number of comparisons it makes is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 15

    Passes make 5 + 4 + 3 + 2 + 1 = 15 = n(n − 1)/2 comparisons. Answering 36 counts n² as if every pass scanned the whole array.
  10. An undirected graph has 9 edges. The sum of the degrees of all its vertices is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 18

    Each edge contributes 1 to the degree of both endpoints: 2 × 9 = 18 (handshake lemma). Answering 9 counts each edge once.
  11. The ReLU activation is applied to an input of −2.5. The output is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0

    ReLU(x) = max(0, x), so any negative input gives 0. Answering 2.5 confuses ReLU with the absolute value.
  12. Before clustering, two feature vectors are x = (2, 7) and y = (8, −1). Their Euclidean distance is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 10

    √(6² + 8²) = √100 = 10. The Manhattan distance 6 + 8 = 14 is the tempting alternative metric.
  13. Which sorting algorithm is usually fastest on an array that is already nearly sorted?

    1. Quicksort with the first element as pivot
    2. Selection sort
    3. Heap sort
    4. Insertion sort
    Show answer

    Answer: D — Insertion sort

    Insertion sort does work proportional to n plus the number of inversions, close to linear here. Quicksort with a first-element pivot degrades towards Θ(n²) on such input, the tempting trap.
  14. Insertion sort is run on [4, 3, 2, 1]. The total number of element shifts (moves of an element one place right) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 6

    Each shift removes one inversion, and a reversed array of 4 has C(4, 2) = 6 inversions. Answering 3 counts only one shift per insertion.
  15. Single-linkage agglomerative clustering is run on the points 1, 2, 6, 7, 15 on a line. The distance at which the final merge occurs is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 8

    Merges happen at 1 ({1, 2} and {6, 7}), then 4 ({1, 2, 6, 7}), and finally 15 joins at its nearest neighbour 7: distance 8. Complete linkage would use the farthest point, 15 − 1 = 14, the tempting alternative.
  16. A neuron has weights (0.5, −1), bias 0.2 and ReLU activation. For the input (2, 1), its output is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0.2

    z = 0.5 × 2 − 1 × 1 + 0.2 = 0.2, and ReLU(0.2) = 0.2. Dropping the bias gives 0, which ReLU would also return for any negative z.
  17. An undirected graph has edges A–B 1, B–C 2, A–C 3, C–D 4 and B–D 5. The weight of its minimum spanning tree is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 7

    Kruskal takes A–B 1 and B–C 2, rejects A–C 3 (cycle), then takes C–D 4: 7. Taking the three cheapest edges blindly (1 + 2 + 3 = 6) forms a cycle and leaves D unconnected.
  18. A fully connected network has 4 inputs, one hidden layer of 8 units and 3 outputs, with a bias on every hidden and output unit. The number of trainable parameters is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 67

    (4 × 8 + 8) + (8 × 3 + 3) = 40 + 27 = 67. Counting weights only gives 56; the biases add 11.
  19. k-means with k = 2 runs on the points 1, 2, 3, 10, 11, 12 starting from centroids 1 and 2 (ties go to the first centroid). After one assignment-and-update step, the second centroid is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 7.6

    Only 1 is nearer centroid 1; the rest go to centroid 2, whose mean is (2 + 3 + 10 + 11 + 12)/5 = 7.6. Assuming the natural split {1, 2, 3} and {10, 11, 12} gives 11, which k-means reaches only after more iterations.
  20. The maximum number of key comparisons made by top-down merge sort on 8 elements (over all input orders) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 17

    Worst-case merges cost (1 + 1 + 1 + 1) + (3 + 3) + 7 = 17, i.e. n⌈log₂n⌉ − 2^⌈log₂n⌉ + 1, confirmed by running all 40 320 orders. Answering 24 uses n log₂ n, which over-counts by one comparison per merge.
  21. Which of the following statements about neural networks are correct? (More than one may be correct.)

    1. Sigmoid units saturate for large |z|, which can make gradients vanish
    2. Backpropagation computes gradients by repeated application of the chain rule
    3. Without non-linear activations, a multi-layer network computes only a linear (affine) function
    4. The derivative of ReLU is 1 for negative inputs
    Show answer

    Answer: A — Sigmoid units saturate for large |z|, which can make gradients vanish; B — Backpropagation computes gradients by repeated application of the chain rule; C — Without non-linear activations, a multi-layer network computes only a linear (affine) function

    The first three are correct. The last is the trap: ReLU is flat (derivative 0) for negative inputs and has slope 1 only for positive inputs.