Skip to content

Commit 4a512ea

Browse files
committed
Adding readme
1 parent 4a6bd11 commit 4a512ea

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed
183 KB
Loading
111 KB
Loading

Topological Sort/README.markdown

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Topological Sort
2+
3+
Topological sort is an algorithm aimed at ordering a directed graph such that for each directed edge *uv* from vertex *u* to vertex *v*, *u* comes before *v*.
4+
5+
## Where is this used?
6+
7+
Let's consider that you want to learn all the algorithms present in the swift-algorithm-club, this might seem daunting at first but we can use topological sort to get things organized.
8+
9+
For e.g. To learn the depth first search algorithm you need to know how a graph is represented. Similarly, to understand how to calculate the length of a binary tree you need to know details of how a tree is traversed. If we were to represent these in the form of a graph it would be as follows:
10+
11+
//add image
12+
13+
If we consider each algorithm to be a node in the graph you'll see dependancies among them i.e. to learn something you might have to know something else first. This is exactly what topological sort is used for, it will sort things out such that you know what to learn first.
14+
15+
## How does it work?
16+
17+
### Step 1: Find all nodes that have in-degree of 0
18+
19+
The in-degree of a node is the number of incoming edges to that node. All nodes that have no incoming edges have an in-degree of 0. These nodes are the starting points for the sort.
20+
21+
If you think about it in the context of the previous example these nodes represent algorithms that don't need anything else to be learnt, hence the sort starts with them.
22+
23+
### Step 2: Use depth first search for traversal
24+
25+
Depth first search is an algorithm that is used to traverse a graph. This algorithm traverses all the child nodes recursively and uses backtracking to find other edges.
26+
27+
To know more about this algorithm please take a look at the explanation here.
28+
29+
### Step 3: Remember all visited nodes
30+
31+
The last step of the sort is to maintain a list of all the nodes that have already been visited.
32+
33+
## Example
34+
35+
Consider the following graph:
36+
37+
*Step 1* Nodes with 0 in-degree: **5, 7, 3**
38+
*Step 2* Depth first search for each without remembering nodes that have already been visited:
39+
40+
Node 3: 3, 8, 9, 10
41+
Node 7: 7, 11, 2, 8, 9
42+
Node 5: 5, 11, 2, 9, 10
43+
44+
*Step 3* Remember nodes already visited in each DFS.
45+
46+
Node 3: 3, 8, 9, 10
47+
Node 7: 7, 11, 2
48+
Node 5: 5
49+
50+
The final sorted order is a concatenation of the above three traversals: **3, 8, 9, 10, 7, 11, 2, 5**

0 commit comments

Comments
 (0)