|
|
|
Forum Member
      
участник
Last Login: 20.01.2007 9:18
Сообщ.: 31,
Visits: 319
|
|
Sorry for my english. (translitom neho4y)
Hello,
I need implement topological sort.
I found info about this type of sorting on
http://en.wikipedia.org/wiki/Topological_sort
I write something like (code below).
But I can't test it .
According to wiki I get error that my graph is not a DAG, so a topological sort is impossible
My code below, Please with what input test it.
Thanks.
------------------MyData.java------------------
public class MyData {
public String job;
public String [] others;
public MyData(String job, String [] other) {
this.job = job;
this.others = other;
}
}
---------------TopSort.java-------------------
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.Iterator;
public class TopSort {
public static String[] topologicalSort(MyData[] data) throws Exception {
/*
* Q ? Set of all nodes with no incoming edges while Q is non-empty do
* remove a node n from Q output n for each node m with an edge e from n
* to m do remove edge e from the graph if m has no other incoming edges
* then insert m into Q if graph has edges then output error message
* (graph has a cycle)
*/
int n = data.length;
Map graph = new HashMap();
Queue q = new LinkedList();
String[] sorted = new String[n];
// Graph construction
for (int i = 0; i < data.length; i++) {
// for each statistic name s
graph.put(data[i].job, new HashSet());
String[] requiredJobs = data[i].others;
for (int j = 0; j < requiredJobs.length; j++) {
// for each String si in requiredStats
((Set) graph.get(data[i].job)).add(requiredJobs[j]);
}
// Initial nodes in q
if (((Set) graph.get(data[i].job)).size() == 0)
q.add(data[i].job);
}
// Getting the nodes in sorted order
int index = 0;
while (q.size() > 0) {
String s = (String) q.remove();
sorted[index++] = s;
Iterator iter = graph.keySet().iterator();
while (iter.hasNext()) {
// for each key in graph
// check if node is not already removed
Object key = iter.next();
if (((Set) graph.get(key)).size() != 0) {
((Set) graph.get(key)).remove(s);
// if this node now has zero incoming edges
if (((Set) graph.get(key)).size() == 0) {
q.add(key);
}
}
}
}
if(index
throw new Exception("Cycle detected, exiting ....");
return sorted;
}
public static void main(String[] args) throws Exception {
MyData d1 = new MyData("job1",new String [] {"job3","job5","job4"});
MyData d2 = new MyData("job3",new String [] {"job5","job6"});
MyData d3 = new MyData("job4",new String [] {"job2","job7"});
MyData d4 = new MyData("job7",new String [] {"job1","job2","job4"});
String [] sorted = TopSort.topologicalSort(new MyData [] {d1,d2,d3,d4});
for (int i = 0; i < sorted.length; i++) {
System.out.println(sorted[i]);
}
}
}
|
|
|
|