Skip to content

Commit cf27c00

Browse files
committed
Fix topological sort bug, improve explanation
When concatenating the results from the individual depth-first searches, the subsequent results need to be prepended, not appended, to the final list.
1 parent 05ef99b commit cf27c00

29 files changed

+245
-161
lines changed

README.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ Special-purpose sorts:
7575
- Bucket Sort
7676
- Counting Sort
7777
- Radix Sort
78-
- [Topological Sort](Topological Sort/) :construction:
78+
- [Topological Sort](Topological Sort/)
7979

8080
Bad sorting algorithms (don't use these!):
8181

Topological Sort/Graph.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,22 @@ public class Graph: CustomStringConvertible {
3030
return nil
3131
}
3232
}
33+
34+
extension Graph {
35+
typealias InDegree = Int
36+
37+
func calculateInDegreeOfNodes() -> [Node : InDegree] {
38+
var inDegrees = [Node : InDegree]()
39+
40+
for (node, _) in adjacencyLists {
41+
inDegrees[node] = 0
42+
}
43+
44+
for (_, adjacencyList) in adjacencyLists {
45+
for nodeInList in adjacencyList {
46+
inDegrees[nodeInList] = (inDegrees[nodeInList] ?? 0) + 1
47+
}
48+
}
49+
return inDegrees
50+
}
51+
}
2.08 KB
Binary file not shown.
25 KB
Loading
2.1 KB
Binary file not shown.

Topological Sort/Images/Example.png

9.09 KB
Loading

Topological Sort/Images/Graph.graffle

2.17 KB
Binary file not shown.

Topological Sort/Images/Graph.png

7.94 KB
Loading
2 Bytes
Binary file not shown.
1.34 KB
Loading

0 commit comments

Comments
 (0)