Created
May 26, 2020 17:39
-
-
Save colibie/79cff533312ceed3a12518c67abbcd98 to your computer and use it in GitHub Desktop.
Code for topological sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Digraph from './Digraph' | |
class topologicalSort { | |
constructor(graph) { | |
this.g = graph; | |
this.vertices = g.V(); | |
this.marked = []; // contains the visited vertices | |
this.postOrder = []; | |
} | |
/** do a depth first search, and then add any vertex returned from, to a stack. In this case, I will use an array and unshift to see my elements in postorder. */ | |
sort() { | |
for (int i = 0; i < vertices; i++) { | |
DFS(i); | |
} | |
return postOrder; | |
} | |
DFS(int v) { | |
if (marked[v]) return; // if the vertex has already been visited, don;t search it | |
marked[v] = true; | |
for (let vertex : g.adj(v)) { // recursively visit all vertices connected to v | |
DFS(vertex); | |
} | |
postOrder.push(v); // add to postOrder array before returning from the visit | |
} | |
run() { | |
Digraph input = new Digraph(7); | |
input.addEdge(0, 1); | |
input.addEdge(1, 4); | |
input.addEdge(0, 5); | |
input.addEdge(0, 2); | |
input.addEdge(6, 0); | |
input.addEdge(6, 4); | |
input.addEdge(3, 5); | |
input.addEdge(3, 4); | |
input.addEdge(3, 6); | |
input.addEdge(3, 2); | |
input.addEdge(5, 2); | |
topologicalSort test = new topologicalSort(input); | |
const postOrder = test.sort() | |
for (let i = postOrder.length - 1; i >= 0; i--) { | |
console.log(value); // 3 6 0 5 2 1 4 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment