Graph algorithms

Hand-drawn hatched terracotta route winding from edge to edge through a dense mesh of cream, sand, umber and moss lines, with two short branches that stop.

A graph algorithm works on a network of vertices joined by edges, such as a road map, a social network or a web of links. When measured, the fastest choice depends less on asymptotic bounds than on how the graph is stored, how often it changes and what is timed. A flat array layout is a strong baseline for a fixed sparse graph, and a simple array heap beat theoretically faster priority queues on a full U.S. road map (Su et al., 2025; Larkin et al., 2014). Indexes built ahead of time answer road-route queries thousands of times faster than plain search, at a cost in preparation time and memory (Bast et al., 2016). The main disputes concern when a priority queue should update entries in place, and whether recent almost-linear-time flow algorithms help in practice.

Storing a graph

Compressed sparse row (CSR) is the measured baseline for a sparse graph that does not change. CSR stores every vertex’s neighbours back to back in one array, with a second array marking where each vertex’s list starts. On eight real graphs, static CSR gave 2.4 to 11.0 times the read-query performance of the dynamic storage methods tested (Su et al., 2025). In another benchmark, an off-the-shelf B-tree container took 1.22 times the runtime of the optimized static layout on average (Wheatman et al., 2024a).

Some layouts that accept updates come close to CSR on reads. A batch-update variant of CSR averaged 1.05 times the static CSR runtime, using 6.25 bytes per edge against 4.44, and peaked at 420 million inserts per second (Wheatman et al., 2024b). CSR++ ran 15% slower than CSR on average in a read-only comparison, and less than 10% slower at 36 threads (Firmli et al., 2020). How updates are grouped also matters: coarse-grained locking lost throughput on small batches, while fine-grained locking suffered contention as batches grew (Su et al., 2025).

Building the layout can cost more than running the algorithm. On randomly labelled inputs, converting an edge list to CSR dominated total time for every algorithm tested except triangle counting (Drescher et al., 2023). The best way to build CSR depends on the degree of the vertices: multi-stage construction reduced contention around high-degree vertices, while single-stage construction suited graphs of lower average degree (Sahu, 2023). Neighbours stored in a hash map per vertex took about four times as long to build as lists up to 16 vertices. From 128 vertices, they took about twice as long (Valiente, 2022).

An adjacency matrix, one row and column per vertex, can pay off when its entries are packed as single bits. In 1998 experiments, a bit-packed matrix typically ran breadth-first search in one twentieth of the time of an integer matrix or less. It crossed over with an adjacency list near a ratio of 33 between vertex count and average degree (Black et al., 1998).

On modern GPUs, bit-level formats save space and time. One stored 491 of 521 binary matrices in less space than floating-point CSR. It sped up a sparse matrix-vector product 2.06 to 2.97 times on average (Chen et al., 2022). Another used on average 53% of the space of storing CSR and its column-wise twin together (Niu & Casas, 2025).

Reordering vertices

Renumbering vertices so that neighbours sit close in memory pays only when the graph is processed many times. A costly ordering, Gorder, cut mean PageRank runtime by 35% on 56 threads, but needed 873 to 6,771 PageRank runs to repay the reordering (Balaji & Lucia, 2018). A cheaper scheme, Degree-Based Grouping, made a single shortest-path run 20.6% slower on average once its own cost was counted. It gave an 11.5% average speedup over eight runs and repaid itself after 2 to 5 PageRank iterations (Faldu et al., 2019).

Traversal

Breadth-first search (BFS) and depth-first search (DFS) do different jobs. BFS finds the fewest-hop path from a source; DFS gives the visiting order behind cycle detection, topological sorting and strongly connected components (Boost.Graph, n.d.b).

The shape of the graph decides which BFS implementation wins. Direction-optimizing BFS switches, when the frontier of active vertices grows large, from pushing out from that frontier to having unvisited vertices look for a parent. This pays on low-diameter graphs, such as social networks, and less on high-diameter ones, such as roads. On a multi-socket server it gave speedups of 2.4 to 4.6 times on real social networks over a strong conventional baseline (Beamer et al., 2012). A GPU implementation was 3.51 times as fast as a CPU library on scale-free graphs, but 3.2 times slower on road and mesh graphs (Yang et al., 2018).

When only reachability matters, dropping strict DFS order allows parallel search. An unordered parallel DFS was 22 times as fast as the Ligra framework on road graphs, while Ligra led on several low-diameter graphs such as Twitter and Friendster (Acar et al., 2015).

Shortest paths

Choosing the algorithm

The kind of edge weight picks the baseline algorithm. Graph libraries use BFS for unweighted graphs, with bidirectional BFS for a single pair of vertices (NetworkX developers, n.d.b). Dijkstra’s algorithm handles nonnegative weights; Bellman–Ford handles negative weights and detects cycles of negative total weight; a directed graph without cycles has a linear-time method (Boost.Graph, n.d.a). For distances between all pairs, Boost.Graph recommends Johnson’s algorithm on sparse graphs with negative weights and Floyd–Warshall on dense graphs (Boost.Graph, n.d.a).

All pairs of vertices Weak evidence: few or small studies support this

Small synthetic benchmarks find that the crossover between running Dijkstra from every vertex and Floyd–Warshall moves with density and weights. On random graphs of 4,096 vertices, repeated Dijkstra narrowly won at 4,096 edges and narrowly lost at 9,410. On scale-free graphs of the same size, it took about half the time of Floyd–Warshall (Zugan et al., 2025). At one edge per vertex, repeated Dijkstra took 2.4% of classic Floyd–Warshall time, and a reachability-list variant 0.7% (Toroslu, 2021).

The range of weights can reverse a result at fixed density. On complete 3,000-vertex graphs, the unmodified Floyd–Warshall took 31.4 s. One variant took 63.5 s with edge costs from 1 to 100, but 14.7 s with costs from 1 to 10 (Lancia & Dalpasso, 2025). Structure also helps. Treewidth measures how close a graph is to a tree; with treewidth fixed at 211, one method ran 9.3 times as fast as Johnson’s algorithm (Planken et al., 2012).

Road networks

Without any preparation, searching from both ends roughly halves the time of plain Dijkstra on a road map. On the Western Europe network, bidirectional Dijkstra averaged about 1.2 seconds per random query against about 2.2 seconds (Bast et al., 2016). A* search adds a lower bound on the remaining distance; ALT computes that bound from distances to a few landmark vertices, with no need for geographic coordinates (Goldberg & Harrelson, 2005).

Indexes built ahead of time trade preparation time and memory for query speed. A contraction hierarchy adds shortcut edges that let a query skip vertices; returning the actual road-by-road route then needs those shortcuts unpacked (Bast et al., 2016). Hub labels store, for each vertex, distances to selected hubs, and answer a query by finding a hub on a shortest path shared by both ends (Blum et al., 2021). The table gives one single-threaded benchmark of distance queries on the Western Europe network (Bast et al., 2016).

MethodPreparationMemoryMean distance query
DijkstraNone0.4 GiB2,195,080 μs
Bidirectional DijkstraNone0.4 GiB1,205,660 μs
Contraction hierarchies5 min0.4 GiB110 μs
Transit-node routing22 min2.5 GiB2.09 μs
Hub labels (uncompressed)37 min18.8 GiB0.56 μs

The ranking changes when the caller needs the full route or short trips. In an independent road benchmark, contraction hierarchies used the least preparation time and space of four approaches and handled both routes and distances well. Adding transit-node routing sped up distance-only queries between far-apart vertices but trailed when returning full paths (Wu et al., 2012). A hub-label variant tuned for long distances answered its local queries four to five times more slowly than its long-range ones (Abraham et al., 2010).

Changing weights and traffic

Customizable methods split the slow, shape-dependent preparation from a fast per-weight step, which helps when one network needs several cost models. With 100-second U-turn penalties on Western Europe, customizable route planning took 12 minutes of shared preparation plus 0.37 seconds per cost model, against 29 minutes for a compact contraction hierarchy. Full-route queries averaged 1.85 ms and 2.37 ms respectively (Bast et al., 2016). A newer labelling method answered cost-only queries in 14.08 μs against 401.2 μs, at twice the customization time and nearly four times the memory of customizable contraction hierarchies (Farhan et al., 2025).

When travel time depends on the time of day, memory becomes the limit. On a European network, one time-dependent index ran out of memory on a 192 GB machine after producing about 150 GB of preprocessed data. Another answered exact queries in under 5 ms on average with about 5.5 GB (Strasser et al., 2021). For live traffic, a guided A* search updated in 20.1 seconds and averaged 25.4 ms per query. It assumes live travel times are never faster than predicted ones (Werner & Zeitz, 2022).

On roads with frequent weight changes, partitioning the index into stages improved throughput by up to two orders of magnitude over applicable baselines (Zhou et al., 2024c).

Priority queues Weak evidence: few or small studies support this

Dijkstra’s and Prim’s algorithms repeatedly remove the closest vertex from a priority queue, so the queue’s speed sets theirs. Simple array heaps beat heaps with better theoretical bounds. On a Dijkstra trace for the full U.S. road map, an array-based 4-ary heap led, and the Fibonacci heap took about three times as long. The pairing heap was the strongest of the Fibonacci-heap family (Larkin et al., 2014). Across the workloads timed, misses in the first-level processor cache tracked wall-clock time most closely of the measures taken (Larkin et al., 2014).

Decrease-key or duplicate entries

Studies disagree on when a queue should update an entry in place. When Dijkstra finds a shorter distance, it can lower that vertex’s key (decrease-key), or insert a new entry and skip the stale one when it surfaces. Duplicates won on sparse random graphs on two processor families, with the gap shrinking as graphs grew denser (Chen et al., 2007). In a series fixed at one million edges, duplicates won at about 0.32 decreases per insertion and decrease-key won at about 4.3 (Chen et al., 2007).

Other workloads favour queues that support decrease-key. An indexed binary heap ran about twice as fast as Python’s duplicate-entry heapq on synthetic workloads built for frequent decreases (Goudarzi et al., 2026). Inside Johnson’s algorithm, a Fibonacci heap overtook a binary heap as edges increased; the binary heap took twice as long on large job-shop graphs (Planken et al., 2012).

Integer keys

With nonnegative integer weights, queues that rely on extracted distances never decreasing can win, but not on every graph. The radix heap uses that property to run Dijkstra in time O(m + n log C). Here m is the number of edges, n the number of vertices and C the largest edge cost (Ahuja et al., 1990). One study’s cyclic buckets ran 1.51 to 1.64 times as fast as its binary heap on three road networks, but its map buckets were slower on dense 5,000-vertex graphs (Davis, 2026). An older benchmark found two comparison-based heaps faster than a standard integer bucket solver (Chen et al., 2007).

A vectorized queue, SimdQuickHeap, was 1.2 to 1.7 times as fast as a radix heap and up to four times as fast as a binary heap. The measurements used one core of an AMD Zen 4 processor, and the queue allocated about five times the memory of the items it held on most benchmarks (Breitling et al., 2026).

Standard-library priority queues

The main standard libraries ship a priority queue without decrease-key on an arbitrary entry.

LanguageStandard queueOrder and updates
Pythonheapq functions on a listSmallest first; version 3.14 added max-heap functions
RustBinaryHeapLargest first; Reverse gives smallest first; peek_mut changes only the top item
JavaPriorityQueueLeast first by natural order or comparator; remove(Object) takes linear time
C++std::priority_queueConfigurable comparison; the top item is read-only
JavaScriptNone among the standard global constructorsNot applicable
(Python Software Foundation, n.d.p; The Rust Project Developers, n.d.a; Oracle, n.d.d; Köppe, 2023; Ecma International, 2026)

The official examples use duplicates instead. Rust’s Dijkstra example pushes a new entry whenever a distance improves and skips popped entries whose cost exceeds the stored distance (The Rust Project Developers, n.d.b). Python’s documentation marks old entries as removed and adds new ones at the revised priority (Python Software Foundation, n.d.p).

Spanning trees and connected components

Minimum spanning trees

No minimum spanning tree algorithm wins across studies; density and implementation decide. Kruskal’s algorithm, which sorts edges, stayed competitive on very sparse graphs, while Filter-Kruskal and Prim’s algorithm with a pairing heap competed on denser ones (Osipov et al., 2009). An earlier benchmark favoured Prim with pairing or binary heaps overall (Moret & Shapiro, 1991). A 2025 Rust comparison found binary-heap Prim fastest across graphs of 100 to 200,000 vertices (Casel & Neubert, 2025).

Other work found Kruskal ahead at large sizes. A Kruskal variant that sorts edges incrementally beat a Prim implementation from 11,000 to 17,000 vertices upward, depending on density (Paredes & Navarro, 2006). Across machines, contracting local edges helped on well-partitioned graphs, while filtering helped Borůvka’s algorithm on higher-degree graphs with poor locality (Sanders & Schimek, 2023).

Union-find

Union-find, also called a disjoint-set structure, tracks which vertices share a component as edges are added: “find” names a vertex’s component and “union” merges two. Rem’s algorithm with splicing led a sequential benchmark that built connected components from a stream of edges. It improved runtime by 52.88% on average over linking by rank with full path compression, and by 28.60% over linking by rank with path halving (Patwary et al., 2010).

In parallel, the best variant depends on the machine and the competitors. On a 72-core machine, the ConnectIt framework’s best static implementation ran 2.36 times as fast as the fastest prior one per graph on average. Without sampling, a compare-and-swap version of Rem’s algorithm did best (Dhulipala et al., 2021). A benchmark on Intel, AMD and ARM machines found competing concurrent variants slightly faster than concurrent Rem, and identified cache misses as critical (Alistarh et al., 2020). General lock-free design is covered in Concurrent data structures.

Flow and matching

The maximum flow problem asks how much can be sent from a source to a sink through edges of limited capacity. The fastest maximum-flow solver depends on the family of graphs. In computer vision, a grid-specific solver was fastest where it applied. No generic parallel implementation consistently beat the serial ones (Jensen et al., 2023). On a wider collection, the FIFO variant of push-relabel won on most graphs, while the highest-label variant did well on the standard DIMACS benchmark (Baumstark et al., 2015).

Head-to-head results between solver families reverse across graph types. Pseudoflow beat push-relabel on every size of one family, taking 2.852 against 8.499 seconds at 65,538 vertices, while push-relabel scaled better on another family (Chandran & Hochbaum, 2009). For minimum-cost flow, the LEMON library’s network simplex was often fastest, but cost scaling ran substantially faster on the largest sparse networks (Kovács, 2013).

Almost-linear algorithms in practice Weak evidence: few or small studies support this

Recent theory proves that exact maximum flow and minimum-cost flow take almost-linear time, but evidence that this beats engineered solvers is preliminary. The bound, m^(1+o(1)) for m edges, holds on directed graphs with polynomially bounded integer demands, costs and capacities (Chen et al., 2025g). A 2026 preprint adapted the framework for minimum-cost flow with heuristics. On one grid family its runtime grew roughly as the graph size to the power 1.04, against 1.48 for LEMON (Schätzle et al., 2026). Its timings assume the solver is handed the best precision setting, and it returned a non-optimal flow at two points (Schätzle et al., 2026).

Matching has a similar gap. A 2026 OpenAI preprint claims an almost-linear randomized algorithm for maximum-cardinality matching in general graphs (OpenAI, 2026a). A third-party prototype implements part of it and states that it does not reproduce the running-time claims (spele1100, n.d.).

Matching in practice

Parallel matching gains depend on the graph. On bipartite graphs, an exact parallel tree-grafting solver averaged seven times the speed of the strongest parallel baseline on a 40-core machine (Azad et al., 2014). On general graphs, one sequential Blossom implementation ran three to five times as fast as a reference code. Its eight-thread parallel version could take three times as long as the sequential one on sparse, community-structured graphs (Schwing et al., 2024).

Graph libraries and benchmarks

What a benchmark times can reverse its ranking. The GAP benchmark suite starts with the graph already loaded, but counts conversion when an implementation needs a different representation (Beamer et al., 2017). The LDBC Graphalytics benchmark times format conversion, the whole job and the algorithm separately, and checks each output against a reference (Iosup et al., 2016). In its 2023 competition, one system took 0.04 s of processing and 27.42 s for the whole job, another 0.20 s and 2.25 s, on different hardware (LDBC Graphalytics Competition Organizers, 2026). General advice on fair benchmarking is in Choosing algorithms and data structures.

Implementations of the same algorithm differ by multiples. In a GAP comparison on shared hardware, each team ran its own framework and the others cross-checked its results (Azad et al., 2020). Galois’s BFS was 3.6 times as fast as the GAP baseline on a high-diameter road graph, using asynchronous execution. GraphIt’s PageRank repaid a conversion to cache-sized subgraphs in 2 to 5 iterations, against about 20 needed to converge (Azad et al., 2020).

In Python, NetworkX was slower than graph-tool and igraph in most tests of a 2025 comparison of five libraries, which used only CPU versions (Amure & Agarwal, 2025). NetworkX can hand calls to faster backends, converting and caching the graph on the way (NetworkX developers, n.d.a). NVIDIA reports about a 31-fold speedup for a betweenness-centrality call on an H100 GPU, timed after the data was read and the graph built (Ratzel, 2023).

Further reading

  • Bast et al. (2016): the survey of route planning, with the shared road benchmark for contraction hierarchies, hub labels and customizable routing.
  • Larkin et al. (2014): the measured case for simple array heaps over Fibonacci and pairing heaps.
  • Chen et al. (2007): decrease-key against duplicate entries in Dijkstra, across densities and processors.
  • Su et al. (2025): a common framework comparing static CSR with dynamic graph storage.
  • Azad et al. (2020): five graph frameworks run on the same hardware with the GAP benchmark.
  • Jensen et al. (2023): a review of serial and parallel maximum-flow solvers measured on vision problems.

Known gaps

What this article cannot tell you yet.

  1. Graph partitioning and community detection are not covered.
  2. Thread-safe priority queues for concurrent graph workloads are not covered.
  3. Union-find specialised for merging adjacent intervals is not covered.
  4. SimdQuickHeap is measured only on its authors’ AMD Zen 4 machine; results on other CPUs are missing.
  5. The 1998 crossover between bit-packed adjacency matrices and adjacency lists is missing a measurement on a modern CPU.
  6. No comparison of Python graph libraries that matches outputs, conversion costs and accelerated NetworkX backends is covered.
  7. Most all-pairs shortest-path, dynamic-index and spanning-tree crossovers rest on single benchmarks; repeated measurements under matched conditions are missing.

References

Solid source
Rated highly trustworthy by the research, and every passage taken from it was found in it.
Weak source
Rated low, or a passage taken from it was not found in it.
Medium trust
Rated medium by the research.
Not checked
Rated high, but its passages could not all be checked against it.
Show all 68 references