Skip to main content

tsort

Function tsort 

Source
pub fn tsort<T>(dag: HashMap<T, HashSet<T>>) -> Result<Vec<T>, TsortError>
where T: Clone + Eq + Hash + Ord,
Expand description

Sorts a directed acyclic graph in topological order.

§Arguments

  • dag - A map from node to its dependencies (nodes it depends on)

§Returns

A sorted list of nodes, or an error if there’s a cycle

§Example

use polyglot_sql::helper::tsort;
use std::collections::{HashMap, HashSet};

let mut dag = HashMap::new();
dag.insert("a", HashSet::from(["b", "c"]));
dag.insert("b", HashSet::from(["c"]));
dag.insert("c", HashSet::new());

let sorted = tsort(dag).unwrap();
// c comes before b, b comes before a
assert!(sorted.iter().position(|x| x == &"c") < sorted.iter().position(|x| x == &"b"));
assert!(sorted.iter().position(|x| x == &"b") < sorted.iter().position(|x| x == &"a"));