Skip to content

Commit 450c4f9

Browse files
authored
Create Topological Sort
1 parent b052612 commit 450c4f9

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Topological Sort

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// "static void main" must be defined in a public class.
2+
public class Main {
3+
public static void main(String[] args) {
4+
int noOfVertices = 5;
5+
int[][] adj=new int[][]{
6+
{0,1,1,0,1},
7+
{0,0,0,1,0},
8+
{0,0,0,1,0},
9+
{0,0,0,0,0},
10+
{0,0,0,0,0}
11+
};
12+
topologicalSort(noOfVertices,adj);
13+
14+
//Graph with Cycle
15+
noOfVertices = 6;
16+
adj=new int[][]{
17+
{0,1,1,0,1,0},
18+
{0,0,0,1,0,0},
19+
{0,0,0,1,0,0},
20+
{0,0,0,0,0,0},
21+
{0,0,0,0,0,1},
22+
{0,0,0,0,1,0}
23+
};
24+
topologicalSort(noOfVertices,adj);
25+
}
26+
27+
static void topologicalSort(int noOfVertices,int[][] adj){
28+
int[] indegree=new int[noOfVertices];
29+
30+
for(int i=0;i<noOfVertices;i++){
31+
for(int j=0;j<noOfVertices;j++){
32+
if(adj[i][j]==1){
33+
indegree[j]++;
34+
}
35+
}
36+
}
37+
38+
System.out.println("In-degree Array : "+Arrays.toString(indegree));
39+
40+
Queue<Integer> q=new LinkedList<>();
41+
42+
for(int i=0;i<noOfVertices;i++){
43+
if(indegree[i]==0){
44+
q.add(i);
45+
}
46+
}
47+
int topologicalOrder=0;
48+
System.out.println("Topological Ordering");
49+
while(!q.isEmpty()){
50+
int vertex=q.remove();
51+
System.out.println(vertex+" -> "+(char)(vertex + 'A'));
52+
topologicalOrder++;
53+
for(int i=0;i<noOfVertices;i++){
54+
if(adj[vertex][i]==1){
55+
indegree[i]--;
56+
if(indegree[i]==0){
57+
q.add(i);
58+
}
59+
}
60+
}
61+
}
62+
63+
if(topologicalOrder!=noOfVertices){
64+
System.out.println("Graph has Cycle");
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)