---
title: 'Topological Heapsort: Heap-Based Topological Sorting'
url: https://www.emergentmind.com/topics/topological-heapsort
type: topic
---

# Topological Heapsort: Heap-Based Topological Sorting

Topological Heapsort denotes a family of comparison-based methods that combine heap-style minimum extraction with a topological or partially ordered structure. In one formulation, developed in “Ordered Dags: HypercubeSort,” a binary heap is generalized to any directed acyclic graph with a single source, yielding a priority queue interface and, for the hypercube DAG, a sorting algorithm with $\mathcal{O}(n\log^2 n)$ comparisons. In a later formulation for sorting under partial information, the feasible frontier of a DAG, and later of an antimatroid, is maintained in a heap ordered by an unknown linear extension, so that the number of comparisons can match the information-theoretic lower bound up to constant factors [1710.00944][2404.04552][2507.13994][2604.12653].

## 1. Terminological scope and conceptual core

The term appears in two technically distinct contexts. In the 2017 ordered-DAG framework, the central object is a labeled DAG with one source vertex, and the heap property is replaced by an edge-wise monotonicity invariant: for a min-structure, labels never decrease along edges. In the 2024–2026 line on sorting under partial information, Topological Heapsort combines Kahn-style maintenance of current sources with a heap whose comparator queries an oracle for an unknown total order extending the input DAG. The 2025 antimatroid generalization replaces DAG sources by the antimatroid frontier of currently available elements [1710.00944][2404.04552][2507.13994].

These formulations share a common structural theme. The admissible next outputs are constrained by a directed or feasible-order topology, while local comparisons determine which admissible element is extracted next. This shared pattern explains the name: the algorithmic control flow is topological, but the selection policy is heap-like.

A persistent source of confusion is the relationship to ordinary topological sorting. Ordinary topological sorting outputs any order consistent with a DAG and requires no key comparisons. Topological Heapsort, in contrast, uses a DAG or a more general feasibility system as a constraint structure while still performing comparison-based sorting. In the ordered-DAG formulation, the keys are arbitrary labels stored on vertices. In the partial-information formulation, the output is the unknown linear extension singled out by oracle comparisons among currently feasible elements [1710.00944][2404.04552].

## 2. Ordered DAGs as generalized heaps

In the ordered-DAG formulation, every vertex $v$ of a DAG $G$ carries an integer key $v.\mathrm{label}$, and the multiset of current labels is $\mathrm{labels}(G)$. For a directed edge $(u \to v)$, the edge is good if $u.\mathrm{label} \le v.\mathrm{label}$ and bad otherwise. A labeled DAG is ordered if all edges are good. This is the DAG generalization of the min-heap property. When $G$ has exactly one source vertex $s$, that source necessarily stores the minimum label in any ordered DAG, because every reachable vertex has label at least $s.\mathrm{label}$ [1710.00944].

Insertion is generalized by the procedure $\mathrm{lowerLabel}(G,v,\mathrm{newLabel})$ for $\mathrm{newLabel} < v.\mathrm{label}$. The label at $v$ is decreased, and any resulting violation is repaired by repeatedly choosing the largest violating previous neighbor, exchanging labels, and continuing from that predecessor. The procedure terminates because the DAG is finite and acyclic, and each swap moves the current vertex strictly upward toward the source. The symmetric operation $\mathrm{raiseLabel}$ increases a key by swapping downward with the smallest violating next neighbor. The ordered-DAG invariant maintained by the paper has two parts: all bad edges, if any, enter the current vertex, and for any previous neighbor $p$ of the current vertex and any next neighbor $n$ of the current vertex, $p.\mathrm{label} \le n.\mathrm{label}$ [1710.00944].

This yields a priority queue interface for any single-source DAG. The constructor initializes all labels to $+\infty$ and maintains a stateful iterator $\mathrm{getNext}()$ that returns vertices in breadth-first order from the source. The operations are:
- $\mathrm{insert}(l)$: take the next vertex and call $\mathrm{lowerLabel}$,
- $\mathrm{getMin}$: return the source,
- $\mathrm{removeMin}$: call $\mathrm{raiseLabel}$ on the source with $+\infty$,
- decrease-key and increase-key: invoke $\mathrm{lowerLabel}$ and $\mathrm{raiseLabel}$ on arbitrary vertices.

If $L(G)$ is the length of the longest simple directed path from the source, and $\Delta_{\mathrm{in}}(G)$ and $\Delta_{\mathrm{out}}(G)$ are the maximum in-degree and out-degree, then
$$
T_{\mathrm{insert}}(G)=O(L(G)\cdot \Delta_{\mathrm{in}}(G)),\qquad
T_{\mathrm{extract}}(G)=O(L(G)\cdot \Delta_{\mathrm{out}}(G)),
$$
with $T_{\mathrm{peek}}(G)=O(1)$. Sorting by $n$ inserts followed by $n$ extract-min operations gives
$$
T_{\mathrm{sort}}(G,n)=O\bigl(n\cdot L(G)\cdot (\Delta_{\mathrm{in}}(G)+\Delta_{\mathrm{out}}(G))\bigr).
$$
The framework therefore generalizes heapsort from complete binary trees to arbitrary single-source DAG topologies [1710.00944].

## 3. HypercubeSort and the path–degree tradeoff

The hypercube instantiation specializes the ordered-DAG framework to the $k$-dimensional hypercube DAG. Its vertices are the $2^k$ subsets of a $k$-element set, and an edge is directed from $U$ to $V$ when $V$ is obtained from $U$ by adding one element. The unique source is the empty set $\varnothing$. A vertex of cardinality $m$ has in-degree $m$, out-degree $k-m$, and every path from the source to that vertex has length $m$. Globally, $L(G)=k$, $\Delta_{\mathrm{in}}(G)=\Delta_{\mathrm{out}}(G)=k$, and the number of vertices is $n=2^k$, so $k=\Theta(\log n)$ [1710.00944].

Substituting these parameters into the general bound gives
$$
T_{\mathrm{sort}}=O(n\cdot k^2)=O(n\log^2 n).
$$
The paper also gives an exact worst-case bound for insertion comparisons when $n=2^k$:
$$
T(n)=\sum_{i=0}^{k}\frac{1}{2}\binom{k}{i}(i+1)i
=2^{k-1}k+2^{k-3}k(k-1)=\Theta(2^k k^2)=\Theta(n\log^2 n).
$$
For general $n$, one may choose $k$ such that $2^k \ge n$ and embed into the next power-of-two hypercube; the asymptotic bound remains $O(n\log^2 n)$ [1710.00944].

The same paper derives a structural inequality for any single-source DAG with $n \ge 2$ vertices:
$$
\frac{1}{n}\log(n!) \le L\cdot (D_{\mathrm{in}}+D_{\mathrm{out}}).
$$
This is obtained by combining the lower bound $\log(n!)$ for comparison-based sorting with the ordered-DAG sorting upper bound $n\cdot L\cdot (D_{\mathrm{in}}+D_{\mathrm{out}})$. The result formalizes a tradeoff between shallowness and degree: reducing the longest-path length forces high in-degree or out-degree, while bounding degrees forces the DAG to be deep. In the ordered-DAG setting, this tradeoff directly controls insertion and extraction cost [1710.00944].

## 4. Sorting under partial information on DAGs

A separate line of work studies sorting under partial information. The input consists of $n$ items and $m$ pre-existing binary comparisons, represented by a DAG $G=(V,E)$. The unknown total order is promised to be a linear extension of the partial order induced by $G$, and $T$ denotes the number of linear extensions, equivalently the number of topological orders of $G$. The information-theoretic lower bound is $\Omega(\log T)$ comparisons [2404.04552].

In this setting, Topological Heapsort combines two classical ideas. Classical topological sorting maintains the frontier of current sources, while heapsort repeatedly extracts a minimum from a heap. The algorithm keeps exactly the current sources in a working-set heap ordered by the unknown total order. At each step it performs $\mathrm{delete\mbox{-}min}$ on the heap, outputs that source, deletes its outgoing arcs by decrementing in-degrees, and inserts any vertices whose in-degree becomes zero. Comparisons occur only among sources, because only sources can be next in any linear extension [2404.04552].

The heap requirement is a working-set bound: insert in $O(1)$ amortized time, and $\mathrm{delete\mbox{-}min}$ of item $x$ in $O(1+\log w(x))$ amortized time, where $w(x)$ is the maximum size of $x$’s working set. Appropriately used pairing heaps and splay-as-heap variants are cited as examples. The base algorithm runs in $O(m+n+\log T)$ time and performs $O(n+\log T)$ comparisons. Its analysis models heap residency intervals by an interval graph, greedily partitions that graph into cliques, proves a lower bound on $\log T$ in terms of the clique sizes, and then bounds the total working-set cost by the same clique expression [2404.04552].

To remove the additive $O(n)$ term in the comparison count, the paper introduces “Topological Heapsort with Insertion.” It first computes and compresses a longest path $P$, stores the original path in an array $L$, and runs the base Topological Heapsort on a reduced DAG $G'$. Each extracted off-path vertex is then inserted into the evolving sorted list $L$ by exponential search followed by binary search. The paper proves that this variant sorts in $O(m+n+\log T)$ time and $O(\log T)$ comparisons, which is optimal up to constant factors. It also notes that the algorithm can be modified to stop after $k$ outputs for the top-$k$ problem, although no explicit theorem with exact top-$k$ bounds is stated [2404.04552].

## 5. Optimal refinements and generalization beyond posets

“Simpler Optimal Sorting from a Directed Acyclic Graph” proves the same asymptotic guarantees, $\Theta(m+n+\log e(P_G))$ time and $\Theta(\log e(P_G))$ queries, but replaces the earlier sophisticated analysis by two brief observations. The first is a longest-path lemma: if a longest directed path has $n-k$ vertices, then $\log e(P_G) \ge k$. The second is an interval-embedding argument that bounds $\sum \log d_i$ by $O(\log e(P_G))$. Algorithmically, the paper extracts a longest path $\pi$, locates for each source the farthest in-neighbor $p_i$ on $\pi$, and uses finger-search insertions guided by the oracle to place the source into the evolving order. The result matches the bounds of the earlier Topological Heapsort line while avoiding advanced charging arguments and sophisticated data structures [2407.21591].

“Sorting under Partial Information with Optimal Preprocessing Time via Unified Bound Heaps” strengthens the preprocessing–query tradeoff. It gives a simple two-phase algorithm, UniTopSort, with preprocessing $O(n+m)$ and sorting $O(\log e(G)+n)$ time and comparisons, and then a final algorithm with preprocessing $O(m)$ and sorting $O(\log e(G))$ time and comparisons. The key data structure is a Unified Bound Heap with $\mathrm{push}(x)$ in amortized $O(1)$ time, first $\mathrm{pop}$ in amortized $O(1)$ time, and subsequent pop of $x$ in amortized
$$
O\Big(\min_{y:\, b(y)<b(x)}\big(1+\log|a(x)-a(y)|+\log(b(x)-b(y))\big)\Big),
$$
where $a(x)$ is the push index and $b(x)$ is the pop index. A longest-path reduction compresses the sorting phase to a subset $Y$ with $|Y| \in O(\log e(G))$, after which only $Y$ is sorted and the full order is reconstructed in $O(\log e(G))$ time [2604.12653].

The antimatroid generalization broadens the scope further. In “Optimal antimatroid sorting,” the allowable orders form $P(A)$ for an antimatroid $A$ on a ground set $\Sigma$, and the frontier becomes
$$
\mathrm{Cont}(A,\alpha)=\{x\in \Sigma\setminus \mathrm{supp}(\alpha)\mid \alpha x\in A\}.
$$
Topological Heapsort is obtained by replacing DAG sources with this frontier and by using a candidate data structure $C$ to maintain newly available elements. The queue time is $O(|\Sigma|+\log |P(S)|)$ for a monotone precedence system $S$, and a refined algorithm based on layers, bottlenecks, trace antimatroids, and an antimatroid-aware merge achieves time $O((C)+\log |P(A)|)$ with $O(\log |P(A)|)$ comparisons. The paper gives optimal algorithms for monotone precedence formulas, perfect elimination orders of chordal graphs, and vertex search orders of a connected rooted graph; it also states that the transcript of Dijkstra’s algorithm matches Topological Heapsort’s transcript on the vertex search antimatroid, yielding a universal-optimality interpretation [2507.13994].

## 6. Relations, distinctions, and limitations

Topological Heapsort is not topological sorting. In the DAG and antimatroid restricted-sorting literature, the partial order or feasibility system narrows the set of admissible next outputs, but comparisons are still necessary to recover the unknown linear extension. In the ordered-DAG formulation, the DAG is not the input partial information at all; it is a container whose local edge-wise invariant generalizes the heap property. These are related uses of the same phrase, but they solve different algorithmic problems [1710.00944][2404.04552].

The comparison to classical heapsort also depends on the formulation. Binary heaps give $\Theta(\log n)$ insertion and extraction cost and $O(n\log n)$ sorting time. HypercubeSort has $O(\log^2 n)$ per operation and $O(n\log^2 n)$ comparisons. By contrast, sorting under partial information can be much easier than unrestricted sorting: if the number of feasible total orders is $T$ or $e(G)$, the lower bound is $\Omega(\log T)$ or $\Omega(\log e(G))$, and the DAG-based and antimatroid-based Topological Heapsort algorithms achieve matching upper bounds up to constant factors [1710.00944][2404.04552][2507.13994][2604.12653].

Several practical and theoretical caveats recur. In the ordered-DAG framework, the single-source condition is required to identify a unique minimum position and support $O(1)$ peek; multiple sources would complicate minimum handling. Equal labels are allowed, but stability is not guaranteed unless additional tie-breaking is enforced. In the partial-information and antimatroid settings, optimality depends on efficient maintenance of the frontier; beyond antimatroids, the 2025 paper states that Topological Heapsort is not optimal in general greedoids, and it lists efficient candidate data structures for richer antimatroids such as convex shellings as an open direction. The 2026 paper similarly identifies dynamic DAGs and simpler heaps achieving the unified bound as open problems [1710.00944][2507.13994][2604.12653].

A final distinction concerns other graph-based sorting methods. “Sorting an Array Using the Topological Sort of a Corresponding Comparison Graph” constructs a comparison graph, uses DFS-based topological sorting, Hamiltonian-path arguments, and graph merges, and obtains a stable $O(n\log n)$ algorithm. It is topological-sort-based, but it does not use the frontier-maintenance priority-queue paradigm that characterizes the later Topological Heapsort literature. This suggests a broader landscape of graph-structured comparison sorting, within which Topological Heapsort is the heap-oriented strand [2009.00098].

Source: https://www.emergentmind.com/topics/topological-heapsort