ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Data Structures & Algorithms
    CC-213
    Progress0 / 37 topics
    Topics
    1. Abstract Data Types2. Complexity Analysis3. Big Oh Notation4. Stacks (Linked Lists and Array Implementations)5. Recursion and analyzing recursive algorithms6. Divide and Conquer Algorithms7. Sorting Algorithms8. Selection Sort9. Insertion Sort10. Merge Sort11. Quick Sort12. Bubble Sort13. Heap Sort14. Shell Sort15. Radix Sort16. Bucket Sort17. Queue18. Dequeuer19. Priority Queues (linked and array implementations of queues)20. Linked List and Its Various Types21. Sorted Linked List22. Searching an Unsorted Array23. Binary Search for Sorted Arrays24. Hashing and Indexing25. Open Addressing and Chaining26. Trees and Tree Traversals27. Binary Search Trees28. Heaps29. M-Way Trees30. Balanced Trees31. Graphs32. Breadth-First Traversal33. Depth-First Traversal34. Topological Order35. Shortest Path36. Adjacency Matrix and Adjacency List Implementations37. Memory Management and Garbage Collection
    CC-213›Topological Order
    Data Structures & AlgorithmsTopic 34 of 37

    Topological Order

    5 minread
    814words
    Beginnerlevel

    Topological Order

    Topological sorting is a linear ordering of the vertices in a directed acyclic graph (DAG) such that for every directed edge u→vu \rightarrow vu→v, vertex uuu comes before vertex vvv in the ordering. This concept is particularly useful in scenarios where there are dependencies between tasks, such as scheduling jobs, resolving symbol dependencies in linkers, or determining the order of course prerequisites in education.

    Key Characteristics

    1. Directed Acyclic Graph (DAG): Topological sorting is only possible for DAGs; if a graph contains cycles, no valid topological ordering exists.
    2. Multiple Orders: A DAG may have multiple valid topological sorts.
    3. Applications: Used in scheduling problems, build systems, course scheduling, and more.

    Algorithm for Topological Sorting

    There are two common methods for performing topological sorting:

    1. Kahn's Algorithm (Using In-Degree)
    2. Depth-First Search (DFS) Based Algorithm

    1. Kahn's Algorithm

    Kahn’s Algorithm uses the concept of in-degree (the number of incoming edges for each vertex). Here’s how it works:

    1. Calculate In-Degree: Compute the in-degree for each vertex.
    2. Initialize a Queue: Enqueue all vertices with in-degree of zero (no dependencies).
    3. Process the Queue:
      • Dequeue a vertex, add it to the topological order.
      • For each adjacent vertex, decrease its in-degree by one.
      • If an adjacent vertex’s in-degree becomes zero, enqueue it.
    4. Check for Completion: If the topological order includes all vertices, return it. If not, a cycle exists.

    2. DFS-Based Algorithm

    The DFS-based algorithm involves using depth-first traversal:

    1. Maintain a Visited List: Keep track of visited vertices to avoid cycles.
    2. Recursion Stack: Use a stack to store the order of vertices as they finish.
    3. Visit Vertices: For each unvisited vertex, perform a DFS, marking vertices as visited.
    4. Store Finish Order: Once all adjacent vertices are visited, push the vertex onto the stack.
    5. Construct Topological Order: Pop vertices from the stack to get the topological order.

    Example: Topological Sorting Using DFS

    Here’s a C++ implementation using the DFS approach:

    #include <iostream>
    #include <vector>
    #include <stack>
    using namespace std;
    
    class Graph {
    private:
        int V; // Number of vertices
        vector<vector<int>> adj; // Adjacency list
    
        void topologicalSortUtil(int v, vector<bool>& visited, stack<int>& Stack) {
            visited[v] = true; // Mark the current node as visited
    
            // Recur for all the vertices adjacent to this vertex
            for (int i : adj[v]) {
                if (!visited[i]) {
                    topologicalSortUtil(i, visited, Stack);
                }
            }
    
            // Push current vertex to stack which stores the result
            Stack.push(v);
        }
    
    public:
        Graph(int v) : V(v), adj(v) {}
    
        void addEdge(int u, int v) {
            adj[u].push_back(v); // Add edge from u to v
        }
    
        void topologicalSort() {
            stack<int> Stack;
            vector<bool> visited(V, false);
    
            // Call the recursive helper function to store Topological Sort
            for (int i = 0; i < V; i++) {
                if (!visited[i]) {
                    topologicalSortUtil(i, visited, Stack);
                }
            }
    
            // Print contents of stack
            cout << "Topological Order: ";
            while (!Stack.empty()) {
                cout << Stack.top() << " ";
                Stack.pop();
            }
            cout << endl;
        }
    };
    
    int main() {
        Graph g(6); // Create a graph with 6 vertices
        g.addEdge(5, 2);
        g.addEdge(5, 0);
        g.addEdge(4, 0);
        g.addEdge(4, 1);
        g.addEdge(2, 3);
        g.addEdge(3, 1);
    
        g.topologicalSort(); // Perform topological sort
    
        return 0;
    }
    

    Explanation of the Code

    1. Graph Class:

      • Contains the number of vertices and an adjacency list.
      • addEdge Function: Adds a directed edge from vertex uuu to vertex vvv.
    2. topologicalSortUtil Function:

      • A recursive utility that performs DFS and pushes the finished vertices onto a stack.
    3. topologicalSort Function:

      • Initializes the visited array and stack.
      • Calls the utility for each unvisited vertex and prints the topological order after popping from the stack.

    Complexity Analysis

    • Time Complexity: O(V+E)O(V + E)O(V+E)

      • Each vertex and edge is processed once.
    • Space Complexity: O(V)O(V)O(V)

      • For the visited list and the stack.

    Applications of Topological Sorting

    1. Task Scheduling: Ordering tasks based on their dependencies.
    2. Course Scheduling: Determining the order in which courses should be taken based on prerequisites.
    3. Build Systems: Managing compilation of files with dependencies.

    Conclusion

    Topological sorting is a fundamental algorithm for directed acyclic graphs that helps in ordering vertices based on dependencies. Understanding how to implement topological sorting, both through Kahn’s algorithm and depth-first search, is essential for solving problems related to scheduling and dependency resolution.

    Previous topic 33
    Depth-First Traversal
    Next topic 35
    Shortest Path

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time5 min
      Word count814
      Code examples0
      DifficultyBeginner