├── README.md └── sorting.js /README.md: -------------------------------------------------------------------------------- 1 | # sorting 2 | Topological sorting is used for ordering tasks or nodes in a directed acyclic graph (DAG) such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering. Here's a JavaScript implementation of topological sorting using depth-first search (DFS): 3 | I defined a Graph class representing the directed graph. 4 | The addEdge method adds an edge between two vertices. 5 | The topologicalSort method performs topological sorting using depth-first search (DFS). It initializes a stack to store the sorted vertices and a visited map to keep track of visited vertices. 6 | I defined a helper DFS function that explores all vertices reachable from a given vertex recursively. 7 | I then performed DFS on each vertex in the graph and push the visited vertices onto the stack. 8 | Finally, I reversed the stack to obtain the topologically sorted order. 9 | You can create a Graph object, add edges between vertices, and then call the topologicalSort method to get the topologically sorted vertices. 10 | -------------------------------------------------------------------------------- /sorting.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor(vertices) { 3 | this.vertices = vertices; 4 | this.adjacencyList = new Map(); 5 | for (let i = 0; i < this.vertices.length; i++) { 6 | this.adjacencyList.set(this.vertices[i], []); 7 | } 8 | } 9 | 10 | addEdge(u, v) { 11 | this.adjacencyList.get(u).push(v); 12 | } 13 | 14 | topologicalSort() { 15 | const visited = new Map(); 16 | const stack = []; 17 | 18 | // Initialize visited map 19 | this.vertices.forEach(vertex => { 20 | visited.set(vertex, false); 21 | }); 22 | 23 | // Depth-first search recursive function 24 | const dfs = (v, visited, stack) => { 25 | visited.set(v, true); 26 | 27 | const neighbors = this.adjacencyList.get(v); 28 | neighbors.forEach(neighbor => { 29 | if (!visited.get(neighbor)) { 30 | dfs(neighbor, visited, stack); 31 | } 32 | }); 33 | 34 | stack.push(v); 35 | }; 36 | 37 | // Perform DFS on each vertex 38 | this.vertices.forEach(vertex => { 39 | if (!visited.get(vertex)) { 40 | dfs(vertex, visited, stack); 41 | } 42 | }); 43 | 44 | // Reverse the order to get topological sort 45 | return stack.reverse(); 46 | } 47 | } 48 | 49 | // Example usage: 50 | const vertices = ['A', 'B', 'C', 'D', 'E', 'F']; 51 | const graph = new Graph(vertices); 52 | graph.addEdge('A', 'B'); 53 | graph.addEdge('A', 'C'); 54 | graph.addEdge('B', 'D'); 55 | graph.addEdge('C', 'D'); 56 | graph.addEdge('D', 'E'); 57 | graph.addEdge('E', 'F'); 58 | 59 | const sortedVertices = graph.topologicalSort(); 60 | console.log("Topologically Sorted Vertices:", sortedVertices); 61 | --------------------------------------------------------------------------------