# Topological Sort In Java

Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of vertices in programming. Here linear ordering of vertices means for every two nodes of the directed acyclic graph, v and u, such that v -> u, node v should always come before u.

### Algorithm & Pseudo Code

Step I: Create the graph by calling createEdge(‘x’,’y’).

Step II: Call the topologicalSorting( )

1. Make a Boolean array (named as visit[ ]) and a stack ;
2. b: Populate the ‘false’ value to all the elements of the vist[] array. The ‘false’ value of an element means that the element is not visited.
3. Invoke the helping function topologicalSortUtility() recursively to keep track of the Topological Sort beginning from all the vertices one by one.

Step III: Define topologicalSortUtil(char node, bool visit[], stack<Character> &stk):

1. Update the Boolean array visit by marking the current node as visited, i.e., ‘true’ value should be added corresponding to the current node.
1. Visit all the vertices adjacent to the current vertex by recursively calling the topologicalSortUtility() method. Ensure that recursion only happens when the adjacent vertex is not visited, i.e.,
1.   In order to store the result, add the current vertex to the stack.

Step IV: In the end, after returning from the helping function, display the contents of the stack.

Java Program
The following code implements Topological sort using the algorithm defined above. The code does the implementation of the following direct acyclic graph.

FileName: TopologicalSortExample.java