-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTopologicalSort.java
More file actions
46 lines (41 loc) · 1.6 KB
/
Copy pathTopologicalSort.java
File metadata and controls
46 lines (41 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.jwetherell.algorithms.graph;
import java.util.ArrayList;
import java.util.List;
import com.jwetherell.algorithms.data_structures.Graph;
/**
* In computer science, a topological sort (sometimes abbreviated topsort or
* toposort) or topological ordering of a directed graph is a linear ordering of
* its vertices such that, for every edge uv, u comes before v in the ordering.
*
* @author Justin Wetherell <phishman3579@gmail.com>
*/
public class TopologicalSort {
private TopologicalSort() {
};
public static final List<Graph.Vertex<Integer>> sort(Graph<Integer> graph) {
List<Graph.Vertex<Integer>> sorted = new ArrayList<Graph.Vertex<Integer>>();
List<Graph.Vertex<Integer>> noOutgoing = new ArrayList<Graph.Vertex<Integer>>();
for (Graph.Vertex<Integer> v : graph.getVerticies()) {
if (v.getEdges().size() == 0) {
noOutgoing.add(v);
}
}
while (noOutgoing.size() > 0) {
Graph.Vertex<Integer> v = noOutgoing.remove(0);
sorted.add(v);
for (Graph.Edge<Integer> e : graph.getEdges()) {
Graph.Vertex<Integer> v2 = e.getFromVertex();
Graph.Vertex<Integer> v3 = e.getToVertex();
if (v3.equals(v)) {
graph.getEdges().remove(e);
v2.getEdges().remove(e);
}
if (v2.getEdges().size() == 0)
noOutgoing.add(v2);
}
}
if (graph.getEdges().size() > 0)
System.out.println("cycle detected");
return sorted;
}
}