XQuery/Topological Sort

Motivation
You have a Directed Acyclic Graph (DAG) to track things such as a dependency graph. You want to sort in input DAG of nodes so that in the output reflects the dependency structure.

The Topological Sort of a Directed Acyclic Graph  puts nodes in a sequence such that every node references only preceding nodes.

This ordering is needed for example in scheduling processes in a Pipeline.

For example, given a DAG defined as

the topological order would be:

The definition of topological order can be simply expressed in XQuery:

A recursive algorithm is also straightforward:

which is invoked as

Explanation
$ordered is initially the original sequence, $ordered is empty. At each iteration, the set of nodes which are dependent only on the ordered nodes are calculated and these are removed from the unordered nodes and added to the ordered nodes.