Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topological Sort.

Similar presentations


Presentation on theme: "Topological Sort."— Presentation transcript:

1 Topological Sort

2 Topological Sort Sorting technique over DAGs (Directed Acyclic Graphs)
It creates a linear sequence (ordering) for the nodes such that: If u has an outgoing edge to v  then u must finish before v starts Very common in ordering jobs or tasks

3 Topological Sort Example
A job consists of 10 tasks with the following precedence rules: Must start with 7, 5, 4 or 9. Task 1 must follow 7. Tasks 3 & 6 must follow both 7 & 5. 8 must follow 6 & 4. 2 must follow 4. 10 must follow 2. Make a directed graph and then do DFS.

4 9 Tasks shown as a directed graph. 1 7 3 8 5 6 4 10 2

5 Topological Sort using DFS
To create a topological sort from a DAG 1- Final linked list is empty 2- Run DFS 3- When a node becomes black (finishes) insert it to the top of a linked list

6 Example 9 1 7 3 8 5 6 4 10 2

7 Example 9 1 7 3 8 5 6 4 10 2

8 Example 9 1 7 3 8 5 6 4 10 2

9 Example 9 1 7 3 8 5 6 4 10 2

10 Example head 9 1 10 7 3 8 5 6 4 10 2

11 Example head 9 1 2, 10 7 3 8 5 6 4 10 2

12 Example head 9 1 2, 10 7 3 8 5 6 4 10 2

13 Example head 9 1 8, 2, 10 7 3 8 5 6 4 10 2

14 Example head 9 1 4, 8, 2, 10 7 3 8 5 6 4 10 2

15 Example head 9 1 4, 8, 2, 10 7 3 8 5 6 4 10 2

16 Example head 9 1 4, 8, 2, 10 7 3 8 5 6 4 10 2

17 Example head 9 1 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

18 Example head 9 1 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

19 Example head 9 1 3, 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

20 Example head 9 1 3, 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

21 Example head 9 1 6, 3, 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

22 Example head 9 1 7, 6, 3, 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

23 Example head 9 1 7, 6, 3, 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

24 Example head 9 1 9, 7, 6, 3, 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

25 Example head 9 1 9, 7, 6, 3, 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

26 Example head 9 1 5, 9, 7, 6, 3, 1, 4, 8, 2, 10 7 3 8 5 6 4 10 2

27 Topological Sort: Summary
head 9 1 5, 9, 7, 6, 3, 1, 4, 8, 2, 10 7 3 The final order or jobs 8 5 6 Time complexity = DFS complexity O(V + E) 4 There can be many orders that meet the requirements 10 2


Download ppt "Topological Sort."

Similar presentations


Ads by Google