{"id":26024,"date":"2017-10-26T09:56:11","date_gmt":"2017-10-26T04:26:11","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26024"},"modified":"2017-10-26T09:59:36","modified_gmt":"2017-10-26T04:29:36","slug":"topological-sorting","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/topological-sorting\/","title":{"rendered":"C++ Algorithm &#8211; Topological Sorting"},"content":{"rendered":"<p>Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. <span id=\"more-117677\"><\/span>Topological Sorting for a graph is not possible if the graph is not a DAG.<\/p>\n<p>For example, a topological sorting of the following graph is \u201c5 4 2 3 1 0\u201d. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is \u201c4 5 2 3 1 0\u201d. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no in-coming edges)<\/p>\n<p><strong><em>Topological Sorting vs Depth First Traversal (DFS)<\/em><\/strong>:<br \/>\nIn DFS, we print a vertex and then recursively call DFS for its adjacent vertices. In topological sorting, we need to print a vertex before its adjacent vertices. For example, in the given graph, the vertex \u20185\u2019 should be printed before vertex \u20180\u2019, but unlike DFS, the vertex \u20184\u2019 should also be printed before vertex \u20180\u2019. So Topological sorting is different from DFS. For example, a DFS of the shown graph is \u201c5 2 3 1 0 4\u201d, but it is not a topological sorting<\/p>\n<p><strong><em>Algorithm to find Topological Sorting:<\/em><\/strong><br \/>\nWe recommend to first see implementation of DFS here. We can modify DFS to find Topological Sorting of a graph. In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices. In topological sorting, we use a temporary stack. We don\u2019t print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of stack. Note that a vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in stack.<\/p>\n<p>Following are C++ and Java implementations of topological sorting. Please see the code for Depth First Traversal for a disconnected Graph and note the differences between the second code given there and the below code.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>C++ Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ A C++ program to print topological sorting of a DAG<br\/>#include&lt;iostream&gt;<br\/>#include &lt;list&gt;<br\/>#include &lt;stack&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ Class to represent a graph<br\/>class Graph<br\/>{<br\/>    int V;    \/\/ No. of vertices&#039;<br\/> <br\/>    \/\/ Pointer to an array containing adjacency listsList<br\/>    list&lt;int&gt; *adj;<br\/> <br\/>    \/\/ A function used by topologicalSort<br\/>    void topologicalSortUtil(int v, bool visited[], stack&lt;int&gt; &amp;Stack);<br\/>public:<br\/>    Graph(int V);   \/\/ Constructor<br\/> <br\/>     \/\/ function to add an edge to graph<br\/>    void addEdge(int v, int w);<br\/> <br\/>    \/\/ prints a Topological Sort of the complete graph<br\/>    void topologicalSort();<br\/>};<br\/> <br\/>Graph::Graph(int V)<br\/>{<br\/>    this-&gt;V = V;<br\/>    adj = new list&lt;int&gt;[V];<br\/>}<br\/> <br\/>void Graph::addEdge(int v, int w)<br\/>{<br\/>    adj[v].push_back(w); \/\/ Add w to v\u2019s list.<br\/>}<br\/> <br\/>\/\/ A recursive function used by topologicalSort<br\/>void Graph::topologicalSortUtil(int v, bool visited[], <br\/>                                stack&lt;int&gt; &amp;Stack)<br\/>{<br\/>    \/\/ Mark the current node as visited.<br\/>    visited[v] = true;<br\/> <br\/>    \/\/ Recur for all the vertices adjacent to this vertex<br\/>    list&lt;int&gt;::iterator i;<br\/>    for (i = adj[v].begin(); i != adj[v].end(); ++i)<br\/>        if (!visited[*i])<br\/>            topologicalSortUtil(*i, visited, Stack);<br\/> <br\/>    \/\/ Push current vertex to stack which stores result<br\/>    Stack.push(v);<br\/>}<br\/> <br\/>\/\/ The function to do Topological Sort. It uses recursive <br\/>\/\/ topologicalSortUtil()<br\/>void Graph::topologicalSort()<br\/>{<br\/>    stack&lt;int&gt; Stack;<br\/> <br\/>    \/\/ Mark all the vertices as not visited<br\/>    bool *visited = new bool[V];<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        visited[i] = false;<br\/> <br\/>    \/\/ Call the recursive helper function to store Topological<br\/>    \/\/ Sort starting from all vertices one by one<br\/>    for (int i = 0; i &lt; V; i++)<br\/>      if (visited[i] == false)<br\/>        topologicalSortUtil(i, visited, Stack);<br\/> <br\/>    \/\/ Print contents of stack<br\/>    while (Stack.empty() == false)<br\/>    {<br\/>        cout &lt;&lt; Stack.top() &lt;&lt; &quot; &quot;;<br\/>        Stack.pop();<br\/>    }<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    \/\/ Create a graph given in the above diagram<br\/>    Graph g(6);<br\/>    g.addEdge(5, 2);<br\/>    g.addEdge(5, 0);<br\/>    g.addEdge(4, 0);<br\/>    g.addEdge(4, 1);<br\/>    g.addEdge(2, 3);<br\/>    g.addEdge(3, 1);<br\/> <br\/>    cout &lt;&lt; &quot;Following is a Topological Sort of the given graph \\n&quot;;<br\/>    g.topologicalSort();<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Following is a Topological Sort of the given graph\r\n5 4 2 3 1 0<\/pre>\n<p><strong>Time Complexity: <\/strong>The above algorithm is simply DFS with an extra stack. So time complexity is same as DFS which is O(V+E).<\/p>\n<p><strong>Applications:<\/strong><br \/>\nTopological Sorting is mainly used for scheduling jobs from the given dependencies among jobs. In computer science, applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula values in spreadsheets, logic synthesis, determining the order of compilation tasks to perform in makefiles, data serialization, and resolving symbol dependencies in linkers [2].<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C++ Algorithm &#8211; Topological Sorting &#8211; Graph Algorithms &#8211; Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[83515,1,74168,73906],"tags":[83607,83605,83609,83608,83604,83606,83610,83611,82146,82385,82145,82149,82457,82144,83589],"class_list":["post-26024","post","type-post","status-publish","format-standard","hentry","category-c-programming-3","category-coding","category-dfs-and-bfs","category-graph-algorithms","tag-algorithm-c-definition","tag-algorithm-c-example","tag-c-algorithm-book","tag-c-algorithm-pdf","tag-c-algorithm-sort","tag-c-algorithm-tutorial","tag-c-stl-algorithm-tutorial","tag-how-to-write-algorithm-for-functions-in-c","tag-topological-sort-algorithm-pseudocode","tag-topological-sort-complexity","tag-topological-sort-example-step-by-step","tag-topological-sort-java","tag-topological-sort-program-in-c","tag-topological-sort-using-dfs","tag-topological-sorting-leetcode"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26024","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26024"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26024\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26024"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26024"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26024"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}