import java.util.ArrayList; import java.util.Random; public class Graph { ArrayList < Node > vertices, L, S; public Graph() { vertices = new ArrayList < Graph.Node > (); } void top() { L = new ArrayList < Node > (); S = new ArrayList < Node > (); ArrayList < ArrayList < Node >> inL = new ArrayList < ArrayList < Node >> (); ArrayList < ArrayList < Node >> outL = new ArrayList < ArrayList < Node >> (); for (int i = 0; i < vertices.size(); i++) { ArrayList < Node > in = new ArrayList < Node > (); for (int j = 0; j < vertices.get(i).inlist.size(); j++) { in .add(vertices.get(i).inlist.get(j)); } inL.add( in ); } for (int i = 0; i < vertices.size(); i++) { ArrayList < Node > out = new ArrayList < Node > (); for (int j = 0; j < vertices.get(i).outlist.size(); j++) { out.add(vertices.get(i).outlist.get(j)); } if (vertices.get(i).outlist.isEmpty()) { S.add(vertices.get(i)); } outL.add(out); } while (!S.isEmpty()) { Node j = S.get(0); L.add(j); S.remove(j); for (int i = 0; i < j.inlist.size(); i++) { Node m = j.inlist.get(i); outL.get(m.index).remove(j); inL.get(j.index).remove(m); if (outL.get(m.index).isEmpty()) { S.add(m); } } } } public Node getNode(int index) { return vertices.get(index); } public void addEdge(Node from, Node to) { from.outlist.add(to); to.inlist.add(from); top(); } public void addNode() { Node node = new Node(); node.index = vertices.size(); vertices.add(node); top(); } public static void main(String args[]) { Graph graph = new Graph(); for (int i = 0; i < 100; i++) { graph.addNode(); } Integer edges[][] = new Integer[150][2]; for (int i = 0; i < 150; i++) for (int j = 0; j < 2; j++) edges[i][j] = -1; Random rand = new Random(); for (int i = 0; i < 150; i++) { boolean edgexists = false; while (!edgexists) { int nodea = rand.nextInt(99); int nodeb = rand.nextInt(99); if (nodea != nodeb) { for (int j = 0; j < 150; j++) { if (edges[j][0] != nodea && edges[j][1] != nodeb) { edges[i][0] = nodea; edges[i][1] = nodeb; System.out.println("Connecting " + i + " edge " + nodea + " with " + nodeb); graph.addEdge(graph.vertices.get(nodea), graph.vertices.get(nodeb)); edgexists = true; break; } } } } } System.out.println("Topologically Sorted graph is: "); for (int i = 0; i < graph.L.size(); i++) { System.out.print(graph.L.get(i).index + "\t"); } } public class Node { ArrayList < Node > inlist, outlist; int index; Node() { inlist = new ArrayList < Node > (); outlist = new ArrayList < Node > (); } } }You may copy the algorithm and compile it online at http://www.compileonline.com/compile_java_online.php. Good luck. And do let me know if you find any errors
Topological Sort
In this post I will show the implementation of Topological sort using java. I have followed the algorithm from wikipedia. http://en.wikipedia.org/wiki/Topological_sorting#Algorithms.