ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP2117Topological Order
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP2117

    Data Structures

    Progress0 / 37 done
    Topics37
    1Abstract Data Types2Complexity Analysis3Big Oh Notation4Stacks (Linked Lists and Array Implementations)5Recursion and analyzing recursive algorithms6Divide and Conquer Algorithms7Sorting Algorithms8Selection Sort9Insertion Sort10Merge Sort11Quick Sort12Bubble Sort13Heap Sort14Shell Sort15Radix Sort16Bucket Sort17Queue18Dequeuer19Priority Queues (linked and array implementations of queues)20Linked List and Its Various Types21Sorted Linked List22Searching an Unsorted Array23Binary Search for Sorted Arrays24Hashing and Indexing25Open Addressing and Chaining26Trees and Tree Traversals27Binary Search Trees28Heaps29M-Way Trees30Balanced Trees31Graphs32Breadth-First Traversal33Depth-First Traversal34Topological Order35Shortest Path36Adjacency Matrix and Adjacency List Implementations37Memory Management and Garbage Collection
    5 min read
    Topic 34 of 37
    Topic Study Note Illustration
    34

    Topological Order

    Topological sorting is a linear ordering of the vertices in a directed acyclic graph (DAG) such that for every directed edge u → v u \rightarrow v...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    5mremaining
    814words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Data Structures