Skip to content

Instantly share code, notes, and snippets.

@ChristopherBilg
Last active October 2, 2023 22:40
Show Gist options
  • Save ChristopherBilg/79e39744f4e8c546b92096fc2179d71a to your computer and use it in GitHub Desktop.
Save ChristopherBilg/79e39744f4e8c546b92096fc2179d71a to your computer and use it in GitHub Desktop.
Simple minimum spanning tree (MST) implementation in JS; note: the cycle checking function works for this small graph, but will need to be implemented in larger graphs
const vertices = ['a', 'b', 'c', 'd'];
const edges = [
{
starting: 'c',
ending: 'd',
weight: 500,
},
{
starting: 'a',
ending: 'b',
weight: 1,
},
{
starting: 'b',
ending: 'c',
weight: 1,
},
{
starting: 'c',
ending: 'd',
weight: 1,
}
];
// Note: I didn't actually implement the cycle checking algorithm,
// but functionally it's the same for the given graph G.
const doesGraphContainAtleastOneCycle = (arr) => {
return false;
};
const findMinimumSpanningTree = () => {
// O(E log E)
let sortedEdges = edges.sort((a, b) => {
if (a.weight < b.weight) return -1;
else if (a.weight > b.weight) return 1;
else return 0;
});
const minimumSpanningTree = [];
while (sortedEdges.length > 0 && minimumSpanningTree.length < (vertices.length - 1)) {
const tempEdge = sortedEdges.shift();
// If a cycle exists with the new edge, then don't push it into the MST array
const tempMST = [...minimumSpanningTree, tempEdge];
if (doesGraphContainAtleastOneCycle(tempMST)) continue;
minimumSpanningTree.push(tempEdge);
}
return minimumSpanningTree.length === (vertices.length - 1)
? minimumSpanningTree
: null;
};
const result = findMinimumSpanningTree();
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment