Breaking Down Complex Algorithms: A Beginner’s Step-by-Step Guide With C and C++ Examples

Six offices, ten cables: how one minimum spanning tree problem breaks into a brute force, a sort, union-find and a loop, with tested C and C++ code.

A small network on the left and an arrow to three separate pieces on the right: sorted cost bars, groups merging into one, and the finished green tree, illustrating an algorithm broken into parts

Ten offices need a network, and there are 20 possible cables between them, each with a price. One way to find the cheapest network is to try every set of 9 cables that could connect them: 167,960 sets. Another is to sort the 20 cables by price and read through them once, keeping each cable that joins two parts not yet connected. Both give the same answer. The second is Kruskal’s algorithm, and it looks clever only until it is taken apart into the three simple pieces it is made of.

This beginner’s guide shows how to break a complex algorithm into pieces you can understand, write and test one at a time. It follows seven steps, from stating the problem precisely to measuring the finished program, and works through one real problem from start to finish in C, with a C++ version at the end. Along the way it explains Big O notation with measured numbers, sorts the main algorithm design strategies, says what P and NP actually mean, and shows four mistakes that break algorithm code. Every program was compiled and run for this article on Ubuntu 24.04 (x86-64) with GCC 13.3 and Clang 18.1.3, and on Windows 11 with MSVC, as C11 and C17 alongside C++17, all with -Wall -Wextra -pedantic -Werror and no warnings. The algorithm’s tests run clean under AddressSanitizer, UndefinedBehaviorSanitizer and Valgrind, and every output block is captured verbatim. The code is in a GitHub repository whose workflow repeats these checks on each commit.

What Does It Mean to Break Down an Algorithm?

Breaking down a complex algorithm means splitting it into small parts that each do one job and can be understood and tested on their own: a clear statement of the problem, a simple solution that is obviously correct, and the few building blocks, such as a sort or a lookup structure, that the fast solution is made from.

Most algorithms that look complex are a short loop around one or two well-known building blocks. Quicksort is a partition step applied recursively. Dijkstra’s shortest-path algorithm is a loop around a priority queue. Kruskal’s minimum spanning tree algorithm, the example in this guide, is a sort, a disjoint-set structure and a loop of about ten lines. Seeing those parts is what turns an algorithm from something to memorize into something to understand.

The Seven Steps at a Glance

  1. State the problem precisely: inputs, outputs, constraints and what “no answer” looks like.
  2. Work through small examples by hand.
  3. Write the simplest correct solution, even if it is far too slow.
  4. Look for structure and choose a strategy: greedy, divide and conquer, dynamic programming, and so on.
  5. Split the solution into small functions that each do one job.
  6. Trace it and test it, piece by piece and against the simple solution.
  7. Measure it, then optimize the part that actually costs time.

The rest of this guide applies each step to one problem.

Step 1: State the Problem Precisely

The problem in plain words: six offices, A to F, can be joined by ten possible cables, each with a cost. Choose cables so that every office can reach every other one, directly or through other offices, at the lowest total cost.

Stated precisely, that is the minimum spanning tree problem:

  • Input: n vertices (the offices, numbered 0 to n − 1) and m weighted edges (the cables), each a pair of vertices and a cost.
  • Output: a set of edges that connects all n vertices with the smallest total weight. Such a set never needs a cycle, because removing any edge of a cycle keeps everything connected and does not raise the cost, so it has exactly n − 1 edges: a tree that spans every vertex.
  • Constraints: costs are integers and may be negative; there may be several edges between the same two vertices.
  • No answer: if the vertices are not all connected to begin with, no spanning tree exists, and the program must say so.

The last line is easy to skip and was the source of a real bug while writing this guide. A first version of the code returned −1 to mean “not connected”, a habit borrowed from search functions that return −1 for “not found”. But a spanning tree with negative costs can genuinely cost −1, or less, so the same value meant two different things. The random tests in step 6 caught it on the first run. The fix was to return the success or failure separately, as bool, and the cost through a pointer.

Step 2: Work Through Small Examples by Hand

The ten possible cables, as the demo program prints them (office pair and cost):

Possible cables (offices A to F, cost):
  A-B  4
  A-C  3
  B-C  1
  B-D  2
  C-D  4
  D-E  2
  E-F  6
  D-F  7
  C-E  5
  B-F  9
Six offices, ten possible cables Numbers are cable costs; green cables form the cheapest network 4 3 1 2 4 2 6 7 5 9 A B C D E F chosen (total 14) skipped or never needed
Figure 1: The six offices and ten possible cables from the worked example. Kruskal’s algorithm and the brute force both choose the five green cables, for a total cost of 14.

Working by hand, the cheapest cables are worth trying first: B-C (1), then B-D and D-E (2 each), then A-C (3). That connects A, B, C, D and E for a cost of 8. The next cheapest, A-B and C-D (4 each), would only join offices that are already connected, so they add cost without connecting anything. C-E (5) is the same. E-F (6) finally reaches F, for a total of 14.

Doing this by hand already shows the idea of the fast algorithm: take cables in order of price, and skip any cable whose two ends are already connected. It also raises the questions the code will need to answer: how to sort the cables, and how to tell quickly whether two offices are already connected.

Step 3: Write the Simplest Correct Solution

Before writing anything clever, write something that is obviously correct. For this problem, that is a brute force: try every set of n − 1 cables, keep the sets that connect all the offices without a cycle, and remember the cheapest. It is slow, but its correctness is easy to argue, and it becomes the reference that the fast version is tested against.

/* Tries every way to choose the remaining `need` edges from edges[from..m). */
static void choose(int n, const Edge *edges, size_t m, size_t from, int need,
                   const Edge **chosen, int count, bool *found, long long *best,
                   unsigned long long *sets)
{
    if (need == 0) {
        (*sets)++;
        DisjointSet ds;
        if (!ds_init(&ds, n))
            return;
        long long total = 0;
        bool tree = true;
        for (int k = 0; k < count && tree; k++) {
            tree = ds_union(&ds, chosen[k]->u, chosen[k]->v);   /* no cycle */
            total += chosen[k]->weight;
        }
        ds_free(&ds);
        if (tree && (!*found || total < *best)) {
            *found = true;
            *best = total;
        }
        return;
    }
    for (size_t i = from; i + (size_t)need <= m; i++) {
        chosen[count] = &edges[i];
        choose(n, edges, m, i + 1, need - 1, chosen, count + 1, found, best, sets);
    }
}

bool mst_brute_force(int n, const Edge *edges, size_t m, long long *cost,
                     unsigned long long *sets_checked)
{
    bool found = false;
    *cost = 0;
    *sets_checked = 0;
    if (n <= 1)
        return n == 0 || n == 1;         /* nothing to join */
    const Edge **chosen = malloc((size_t)(n - 1) * sizeof *chosen);
    if (chosen == NULL)
        return false;
    choose(n, edges, m, 0, n - 1, chosen, 0, &found, cost, sets_checked);
    free(chosen);
    return found;
}

choose builds each set of n − 1 edges recursively, and each finished set is checked with the same disjoint-set structure described in step 5. For the six offices it checks 252 sets and finds the same total as the hand calculation:

Brute force: cheapest network costs 14, after checking 252 sets of 5 cables

The brute force is not wasted work. It pins down what “correct” means in code, and it will check the fast version on thousands of random inputs.

Step 4: Look for Structure and Choose a Strategy

The hand calculation in step 2 made one choice at a time, always the cheapest cable still useful, and never went back on a choice. That is the signature of a greedy algorithm. Greedy choices are not always safe; they are safe here because of a property of spanning trees: the cheapest edge that crosses between two separate groups of vertices can always be part of some minimum spanning tree. Kruskal’s 1956 paper, “On the shortest spanning subtree of a graph and the traveling salesman problem”, describes the method.

Recognizing which strategy fits is the core skill in breaking down algorithms. Most problems a beginner meets fall into a handful of families:

StrategyThe ideaSigns it fitsExample on MYCPLUS
Brute forceTry every possibilitySmall inputs; a reference for testingStep 3 above
GreedyTake the best-looking choice and never undo itA choice that can be proved safeKruskal’s algorithm
Divide and conquerSplit into independent halves, solve each, combineThe halves do not overlapQuicksort, merge sort
Dynamic programmingSolve each overlapping subproblem once and store itThe same subproblems recurThe knapsack problem, longest common subsequence
BacktrackingBuild a solution step by step, undo a step that leads nowhereConstraints rule out most partial solutionsThe eight queens puzzle
Graph searchExplore vertices in a useful orderThe data is a network of connectionsShortest path algorithms

The 0/1 knapsack problem shows why the strategy matters: a greedy choice by value per kilogram looks just as natural there, and gives a wrong answer, which is why knapsack needs dynamic programming. A strategy is a hypothesis about the problem, and step 6 is where it gets tested.

Step 5: Split the Solution Into Small Functions

The greedy plan needs three things, and each becomes a function, or a small group of functions, with one job.

Piece 1: a disjoint-set (union-find) structure answers “are these two offices already connected?” Each office starts in a group of its own. ds_find returns a group’s representative, and ds_union merges two groups, returning false if they were already the same group, which is exactly the cycle check the greedy loop needs.

int ds_find(DisjointSet *ds, int x)
{
    while (ds->parent[x] != x) {
        ds->parent[x] = ds->parent[ds->parent[x]];   /* path halving */
        x = ds->parent[x];
    }
    return x;
}

bool ds_union(DisjointSet *ds, int a, int b)
{
    a = ds_find(ds, a);
    b = ds_find(ds, b);
    if (a == b)
        return false;                    /* already connected: a cycle */
    if (ds->size[a] < ds->size[b]) {     /* hang the smaller tree below */
        int t = a;
        a = b;
        b = t;
    }
    ds->parent[b] = a;
    ds->size[a] += ds->size[b];
    return true;
}

Two small details keep it fast. Path halving in ds_find points each vertex visited at its grandparent, so later searches take shorter paths, and union by size hangs the smaller group below the larger one, so the trees stay shallow. With both, a long sequence of operations costs almost constant time per operation; Tarjan (1975) proved the bound for this family of methods. The third mistake later in this guide measures what happens without them.

Piece 2: sorting the edges by cost, with qsort and a comparison function:

static int by_weight(const void *x, const void *y)
{
    const Edge *a = x, *b = y;
    if (a->weight != b->weight)
        return (a->weight > b->weight) - (a->weight < b->weight);
    if (a->u != b->u)                    /* ties: a fixed order, so the */
        return (a->u > b->u) - (a->u < b->u);   /* result is repeatable */
    return (a->v > b->v) - (a->v < b->v);
}

The comparison returns −1, 0 or 1 by comparing, never by subtracting, for a reason shown in the mistakes section. Ties are broken by the vertex numbers, so the result is the same on every platform, which keeps the expected outputs in the tests stable.

Piece 3: the greedy loop ties them together:

bool kruskal(int n, Edge *edges, size_t m, Edge *tree, long long *cost)
{
    DisjointSet ds;
    *cost = 0;
    if (n <= 1)
        return n == 0 || n == 1;         /* nothing to join */
    if (!ds_init(&ds, n))
        return false;
    sort_edges(edges, m);
    int taken = 0;
    for (size_t i = 0; i < m && taken < n - 1; i++) {
        if (ds_union(&ds, edges[i].u, edges[i].v)) {   /* joins two parts */
            tree[taken++] = edges[i];
            *cost += edges[i].weight;
        }
    }
    ds_free(&ds);
    return taken == n - 1;
}

With the pieces in place, the algorithm itself is ten lines that read almost like the hand calculation: sort, then take every edge that joins two separate groups, until n − 1 edges are taken. If the loop runs out of edges first, the graph was not connected.

Step 6: Trace It and Test It Against the Brute Force

A trace prints the decisions the algorithm makes, so they can be compared with the hand calculation from step 2. The demo program runs the same loop with a line of output per edge:

static void trace(int n, Edge *edges, size_t m)
{
    DisjointSet ds;
    if (!ds_init(&ds, n))
        return;
    sort_edges(edges, m);
    int taken = 0;
    long long total = 0;
    for (size_t i = 0; i < m && taken < n - 1; i++) {
        const Edge *e = &edges[i];
        printf("  %c-%c %2d  ", NAMES[e->u], NAMES[e->v], e->weight);
        if (ds_union(&ds, e->u, e->v)) {
            taken++;
            total += e->weight;
            printf("take   (cables so far: %d, cost %lld)\n", taken, total);
        } else {
            printf("skip   (%c and %c are already connected)\n", NAMES[e->u], NAMES[e->v]);
        }
    }
    ds_free(&ds);
}

Output for the six offices:

Kruskal, cheapest cable first:
  B-C  1  take   (cables so far: 1, cost 1)
  B-D  2  take   (cables so far: 2, cost 3)
  D-E  2  take   (cables so far: 3, cost 5)
  A-C  3  take   (cables so far: 4, cost 8)
  A-B  4  skip   (A and B are already connected)
  C-D  4  skip   (C and D are already connected)
  C-E  5  skip   (C and E are already connected)
  E-F  6  take   (cables so far: 5, cost 14)

Kruskal's network (cost 14):
  B-C  1
  B-D  2
  D-E  2
  A-C  3
  E-F  6
Same cost as the brute force: yes

The trace matches the hand calculation step for step, and the total matches the brute force. One example is not a test, though. The test program checks each piece on its own (the disjoint sets, the sort with extreme values such as INT_MIN and INT_MAX, empty and disconnected graphs), then compares Kruskal’s answer with the brute force on 5,000 small random graphs with negative costs, repeated edges, loops and disconnected graphs, and with a separate implementation of Prim’s algorithm on 300 larger graphs of up to 300 vertices:

small random graphs where Kruskal matches the brute force: 5000 of 5000
larger random graphs where Kruskal matches Prim's algorithm: 300 of 300
0 failed

The two kinds of test catch different mistakes. In the mutation tests at the end of this guide, a ds_find that follows only one parent link passed every small graph and was caught only by the larger ones, where the groups grow deep enough for the shortcut to matter.

Step 7: Measure It, Then Optimize the Part That Matters

Big O notation describes how the work an algorithm does grows with the size of its input, ignoring constant factors. The brute force and Kruskal’s algorithm show the difference between exponential and near-linear growth on the same problem. The demo counts the work for networks of n offices with 2n possible cables:

Work as the network grows (n offices, 2n possible cables):
  n cables       brute-force sets   Kruskal sorts
  4      8                     56        8 cables
  6     12                    792       12 cables
  8     16                  11440       16 cables
 10     20                 167960       20 cables
 12     24                2496144       24 cables

Each time two offices are added, the brute force has to check about 14 times as many sets: 2,496,144 for 12 offices, and it would need over 37 million for 14. Kruskal’s algorithm sorts the cables, which takes on the order of m log m comparisons for m cables, and then reads each one once. Its running time is O(m log m); the brute force’s is exponential.

Big ONameWhat doubling the input doesExample
O(1)ConstantNothingReading one array element
O(log n)LogarithmicAdds one stepBinary search
O(n)LinearDoubles the workLinear search
O(n log n)LinearithmicA bit more than doubles itMerge sort, Kruskal’s algorithm
O(n²)QuadraticQuadruples itBubble sort and insertion sort
O(2ⁿ) and worseExponentialSquares it, or moreTrying every subset, as in step 3

Time and space are separate costs. Kruskal’s algorithm needs O(n) extra memory for the disjoint sets, on top of the edge list. Many algorithms trade one for the other: dynamic programming spends memory on a table to avoid recomputing answers.

Big O says how the work grows, not where the time goes, so the last step is to measure. The benchmark times the two parts of Kruskal’s algorithm separately, on random connected graphs with four edges per vertex.

SettingValue
Date testedNovember 23, 2026
HardwareCloud VM, 2 vCPUs, Intel Xeon @ 2.10 GHz
Operating systemUbuntu 24.04.5 LTS, x86-64
CompilerGCC 13.3.0, CMake Release build (-O3 -DNDEBUG)
InputRandom connected graphs, 4 edges per vertex, costs 0 to 999,999
What is timedsort_edges (C library qsort) and the union-find loop, separately
StatisticMedian of 5 runs; one machine, single-threaded, no CPU pinning
 vertices     edges    sort ms    union-find ms   sort share
    10000     40000        5.9              0.2          96%
   100000    400000       74.7              2.9          96%
  1000000   4000000      894.1             93.8          91%

Sorting took 91 to 96 percent of the time. At a million vertices and four million edges, the sort took 894 ms and the whole union-find loop 94 ms. So a faster disjoint-set structure would barely change the total, while a faster sort would: for example, a radix sort for integer costs, or no sort at all if the edges arrive already in order. Measuring first is what tells you which piece to work on. The same benchmark built with MSVC on a Windows 11 machine gave the same picture: sorting took 92 to 94 percent of the time (654.8 ms against 56.8 ms at a million vertices). Without the two speed-ups inside the disjoint sets, though, the picture changes completely, as the third mistake below shows.

What P and NP Mean (and Why Brute Force Is Not Always Avoidable)

The minimum spanning tree problem has a fast algorithm, but not every problem does, and it helps to know the vocabulary.

  • P is the class of problems that can be solved in polynomial time, such as O(n²) or O(m log m). The minimum spanning tree is in P.
  • NP is the class of problems whose proposed solutions can be checked in polynomial time. Every problem in P is in NP. The decision version of the traveling salesman problem, “is there a round trip through all these cities shorter than k?”, is in NP: given a route, checking its length is easy. No polynomial-time algorithm for it is known.
  • NP-complete problems are the hardest problems in NP: a polynomial-time algorithm for any one of them would give one for all of NP. The traveling salesman decision problem is one.
  • P versus NP, whether every problem whose solution is easy to check is also easy to solve, is unproved either way. It is one of the Clay Mathematics Institute’s Millennium Prize Problems, with $1 million for a solution.

NP-complete problems are not unsolvable. They can be solved exactly, by brute force or smarter exhaustive search, for small inputs, and approximately, by heuristics, for large ones. The title of Kruskal’s paper links the two worlds: a minimum spanning tree is fast to find, and with non-negative costs it gives a quick lower bound on the length of the best traveling salesman tour, because removing one edge from any tour leaves a spanning tree.

Four Mistakes When Breaking Down an Algorithm

1. Keeping the greedy choice but dropping its safety check

The greedy idea is “take the cheapest cables”. Taking the n − 1 cheapest cables and stopping, without the cycle check, produces this:

/* no_cycle_check.c - "greedy" without its safety check: take the n - 1
 * cheapest cables and stop. The total is lower than the true minimum because
 * the result is not a spanning tree at all. */
#include <stdio.h>
#include <stdlib.h>

typedef struct { int u, v, weight; } Edge;

/* Cheapest first; equal costs in vertex order, because qsort is not stable
 * and the C libraries disagree on how to order ties. */
static int by_weight(const void *x, const void *y)
{
    const Edge *a = x, *b = y;
    if (a->weight != b->weight)
        return (a->weight > b->weight) - (a->weight < b->weight);
    if (a->u != b->u)
        return (a->u > b->u) - (a->u < b->u);
    return (a->v > b->v) - (a->v < b->v);
}

/* Which offices a set of cables reaches from office 0 (repeated scans). */
static int reached(const Edge *e, int count)
{
    int seen[8] = {1}, total = 1, changed = 1;
    while (changed) {
        changed = 0;
        for (int i = 0; i < count; i++)
            if (seen[e[i].u] != seen[e[i].v]) {
                seen[e[i].u] = seen[e[i].v] = 1;
                total++;
                changed = 1;
            }
    }
    return total;
}

int main(void)
{
    Edge cables[] = {
        {0, 1, 4}, {0, 2, 3}, {1, 2, 1}, {1, 3, 2}, {2, 3, 4},
        {3, 4, 2}, {4, 5, 6}, {3, 5, 7}, {2, 4, 5}, {1, 5, 9},
    };
    const int n = 6;
    qsort(cables, sizeof cables / sizeof cables[0], sizeof cables[0], by_weight);
    int cost = 0;
    printf("the %d cheapest cables:", n - 1);
    for (int i = 0; i < n - 1; i++) {
        printf(" %c-%c", "ABCDEF"[cables[i].u], "ABCDEF"[cables[i].v]);
        cost += cables[i].weight;
    }
    printf("\ncost %d, offices connected to A: %d of %d\n", cost, reached(cables, n - 1), n);
    return 0;
}

Output:

the 5 cheapest cables: B-C B-D D-E A-C A-B
cost 12, offices connected to A: 5 of 6

A cost of 12 looks like an improvement on 14, but the five cables include the cycle A-B-C and leave office F unconnected. A greedy algorithm is only as correct as the rule that makes its choice safe; here the rule is “skip any cable that would close a cycle”. Comparing the result with the brute force, or simply checking that the output is a spanning tree, catches this at once.

2. A comparison function that subtracts

return a->weight - b->weight; is a common way to write a qsort comparator, and it works as long as the difference fits in an int:

/* subtract_compare.c - a qsort comparator written as a subtraction. It works
 * for small costs, but a - b overflows when the costs are far apart, and
 * then the edges come out in the wrong order. */
#include <stdio.h>
#include <stdlib.h>

typedef struct { int u, v, weight; } Edge;

static int by_weight_subtract(const void *x, const void *y)
{
    return ((const Edge *)x)->weight - ((const Edge *)y)->weight;   /* overflows */
}

static int by_weight_compare(const void *x, const void *y)
{
    int a = ((const Edge *)x)->weight, b = ((const Edge *)y)->weight;
    return (a > b) - (a < b);
}

static void show(const char *label, int (*cmp)(const void *, const void *))
{
    Edge e[] = {{0, 1, 2000000000}, {1, 2, -2000000000}, {0, 2, 5}};
    qsort(e, 3, sizeof e[0], cmp);
    printf("%-11s", label);
    for (int i = 0; i < 3; i++)
        printf(" %11d", e[i].weight);
    printf("\n");
}

int main(void)
{
    show("subtract:", by_weight_subtract);
    show("compare:", by_weight_compare);
    return 0;
}

Output with GCC 13.3 and Clang 18.1.3 on Linux:

subtract:    2000000000 -2000000000           5
compare:    -2000000000           5  2000000000

2,000,000,000 − (−2,000,000,000) overflows, which is undefined behaviour in C, and here it wrapped to a negative number, so the comparator claimed that 2,000,000,000 is smaller than −2,000,000,000. The sort put the most expensive edge first. Neither compiler warned, even with -Wconversion, and GCC’s -fanalyzer was silent too. UndefinedBehaviorSanitizer stops the program at the subtraction (reports on this page are shortened to the file name and message):

subtract_compare.c:11:38: runtime error: signed integer overflow: 2000000000 - -2000000000 cannot be represented in type 'int'

Comparing with (a > b) - (a < b) gives −1, 0 or 1 without any arithmetic that can overflow.

3. A building block without its speed-ups

The disjoint-set structure is correct without union by size and path halving, just slow in the wrong cases. This program joins 20,000 vertices one after another, then looks each one up, and counts the parent links followed:

static int find(int x)
{
    while (parent[x] != x) {
        if (smart)
            parent[x] = parent[parent[x]];   /* path halving */
        x = parent[x];
        steps++;
    }
    return x;
}

static void unite(int a, int b)
{
    a = find(a);
    b = find(b);
    if (a == b)
        return;
    if (smart && size[a] < size[b]) {        /* union by size */
        int t = a;
        a = b;
        b = t;
    }
    if (smart) {
        parent[b] = a;                       /* the smaller tree goes below */
        size[a] += size[b];
    } else {
        parent[a] = b;                       /* the old set goes below */
    }
}

Output:

20000 vertices joined in a row, then each one found:
no balancing, no path compression:  199990000 links followed
union by size and path halving:         39997 links followed

Joining in a row, with the old group always placed below the new vertex, builds a single chain 20,000 long, and the lookups walk 199,990,000 links in total, which is n(n − 1)/2. With the two speed-ups the same work takes 39,997 links. The naive version gives the same answers, so tests that only check answers never notice; a timing or a count like this one does.

4. A “special value” that is also a real answer

Step 1 described this one: −1 meant “not connected” until a graph with negative costs had a minimum spanning tree that cost −1. Any time a function’s result type has no value left over for “no answer”, return the answer and the success separately, as kruskal does, or use a type built for it, such as std::optional in C++.

Checking the tests with deliberate mistakes

tests/mutations.py puts each of eight plausible mistakes into a copy of mst.c, builds the tests against it with AddressSanitizer and UndefinedBehaviorSanitizer, and records how they fail. One further change affects only speed and must pass:

mistake                                          result
cycles not rejected                              caught: FAILED line 107: n=5 m=12: kruskal tree -31, brute force tree -16
find follows only one parent link                caught: FAILED line 177: n=120 m=391: kruskal -74352154, prim -70420112
path halving points a vertex at itself           caught: FAILED line 68: 0 and 3 are already joined
edges sorted most expensive first                caught: FAILED line 74: sort with extreme weights
comparator written as a subtraction              caught: UBSan at mst.c:62: signed integer overflow
cheapest edge skipped                            caught: FAILED line 87: negative weights
disconnected graph reported as a tree            caught: FAILED line 82: two separate parts have no spanning tree
cost counts every edge examined                  caught: FAILED line 107: n=5 m=12: kruskal tree -34, brute force tree -16
union by size reversed                           passes: still correct
mistakes the tests miss: 0

Every mistake was caught. Two results are worth noting: the one-link ds_find was caught only by the larger random graphs, as described in step 6, and reversing union by size passed, correctly, because it changes how deep the trees get but not which vertices end up connected.

The Same Algorithm in C++

The C++17 version keeps the same three pieces. std::sort with a lambda takes the place of qsort and its comparison function, the disjoint sets become a class, and std::optional<Tree> takes the place of the separate success flag: an empty optional means the graph is not connected.

// Piece 1: which vertices are already connected.
class DisjointSet {
public:
    explicit DisjointSet(int n) : parent_(static_cast<std::size_t>(n)), size_(static_cast<std::size_t>(n), 1)
    {
        std::iota(parent_.begin(), parent_.end(), 0);
    }

    int find(int x)
    {
        while (parent_[idx(x)] != x) {
            parent_[idx(x)] = parent_[idx(parent_[idx(x)])];   // path halving
            x = parent_[idx(x)];
        }
        return x;
    }

    bool unite(int a, int b)   // false if a and b were already connected
    {
        a = find(a);
        b = find(b);
        if (a == b)
            return false;
        if (size_[idx(a)] < size_[idx(b)])
            std::swap(a, b);
        parent_[idx(b)] = a;
        size_[idx(a)] += size_[idx(b)];
        return true;
    }

private:
    static std::size_t idx(int x) { return static_cast<std::size_t>(x); }
    std::vector<int> parent_, size_;
};

struct Tree {
    std::vector<Edge> edges;
    long long cost = 0;
};

// Pieces 2 and 3: sort, then take every edge that joins two separate parts.
// std::nullopt means the graph is not connected.
std::optional<Tree> kruskal(int n, std::vector<Edge> edges)
{
    std::sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {
        return std::tie(a.weight, a.u, a.v) < std::tie(b.weight, b.u, b.v);
    });
    DisjointSet sets(n);
    Tree tree;
    for (const Edge& e : edges) {
        if (static_cast<int>(tree.edges.size()) == n - 1)
            break;
        if (sets.unite(e.u, e.v)) {
            tree.edges.push_back(e);
            tree.cost += e.weight;
        }
    }
    if (n > 0 && static_cast<int>(tree.edges.size()) != n - 1)
        return std::nullopt;
    return tree;
}

std::tie(a.weight, a.u, a.v) < std::tie(b.weight, b.u, b.v) compares by weight, then by the vertices, without any subtraction. The program prints the same network as the C demo:

Kruskal's network (cost 14):
  B-C  1
  B-D  2
  D-E  2
  A-C  3
  E-F  6

Run with --test, it compares itself with a brute force that tries every subset of edges as a bit mask:

random graphs where Kruskal matches the brute force: 3000 of 3000

Key Takeaways

  • Most complex algorithms are a short loop around one or two well-known building blocks. Kruskal’s algorithm is a sort, a disjoint-set structure and ten lines of loop.
  • State the problem precisely, including what “no answer” looks like. Using −1 for “not connected” failed as soon as costs could be negative.
  • Write the brute force first. It checked 252 sets for six offices and became the reference that tested 5,000 random graphs.
  • Choose the strategy from the problem’s structure: greedy, divide and conquer, dynamic programming, backtracking or graph search, and test the choice.
  • Big O decides what scales: 2,496,144 sets for 12 offices by brute force, 24 cables sorted and read once by Kruskal.
  • Measure before optimizing: sorting took 91 to 96 percent of Kruskal’s time, while union-find without its speed-ups followed 199,990,000 links instead of 39,997.

Frequently Asked Questions

Conclusion

Complex algorithms rarely stay complex once they are taken apart. Underneath Kruskal’s algorithm are a sort, a way to remember which offices are connected, and a rule for which cable to take next, each simple enough to write and test in an afternoon. The skill worth practising is not memorizing algorithms but finding those pieces: stating the problem exactly, solving it slowly first, and recognizing the strategy that makes it fast.

The other half of the skill is distrust. A brute force to compare against, tests on inputs you did not choose, and a measurement before any optimization caught every mistake in this guide, including one in its own first draft. More algorithms broken down the same way, with tested C and C++ code, are in the algorithms section.

Source Code and Tests

Minimum spanning tree build status

All programs on this page are in the graphs/minimum-spanning-tree directory of the MYCPLUS C examples repository, with the C++ version in its cpp folder.

Build and test:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

What the build checks. The C code compiles with GCC and Clang under C11 and C17, and with MSVC /W4 /WX; the C++17 version compiles alongside it; warnings are errors. CTest runs the piece-by-piece tests, 5,000 random graphs against the brute force and 300 against Prim’s algorithm, the C++ self-test on 3,000 graphs, and compares the demo, the C++ program and the pitfalls with their expected output. On Linux the workflow also runs every test under AddressSanitizer and UndefinedBehaviorSanitizer, checks that UBSan stops the subtracting comparator, and checks that each deliberate mistake is caught. It does not run the timing benchmark, whose figures came from one machine.

What I Verified

The example directory contains run_all.sh for Ubuntu and run_all.ps1 for Windows, which run every check below; both build in a temporary directory, so nothing is left in the repository.

CheckUbuntu 24.04Windows 11 (MSVC)
Build and CTest, GCC 13.3 and Clang 18.1.3, C11 and C17 with C++17Pass (7 of 7 tests)Not applicable
Build with MSVC /W4 /WX, C11 and C17 with C++17, and CTestNot applicablePass (C11 and C17, 6 of 6 tests each)
5,000 graphs against the brute force, 300 against Prim’s algorithmPass (0 failed)Pass
C++ self-test, 3,000 graphsPass (3,000 of 3,000)Pass
AddressSanitizer and UndefinedBehaviorSanitizer, every testPass (GCC)Not applicable
UBSan stops the subtracting comparatorPassNot applicable
Valgrind on the C tests and the C++ self-testPass (0 errors, no leaks)Not applicable
Eight mutations caught, one harmless change passesPassNot applicable
BenchmarkRun on the cloud VM, figures aboveRun with MSVC /O2; see the note above

Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Clang’s sanitizers on the test machine (they run in CI), and graphs larger than four million edges.

Scroll to Top