×

SQL Topological Sorting

It is for Directed Acyclic Graph, which linearly describes the ordering of graphs. It is not possible for all graphs, it is possible for only Directed acyclic graphs.

Applications of Topological Sorting:

  • Find cycles of a graph.
  • Deadlock detection of Operating system.
  • Resolution of dependency.
  • Ordering of sentences.
  • Analysis of critical path.
  • Problem with the course schedule.

Java Code for Topological sorting:

import java.io.*;
import java.util.*;
class ConstructingGraph
 {
    private int Vect;
    private ArrayList < ArrayList <Integer> > ad;
   ConstructingGraph (int vec)
    {
        Vec = vec;
        ad = new ArrayList < ArrayList <Integer> >(v);
        for (int i = 0; i < vec; ++i)
            ad. ad (new ArrayList <Integer> ());
    }
    void adEd (int vec, int wi) 
  { 
    adj. ge (v). add (w); 
   }
    void topologicalSort (int vec, boolean visit[], Stack <Integer> sta)
    {
        visit [v] = true;
        Integer j;
        Iterator <Integer> iter = adj. get (v). iterator();
        while (iter. hasNext()) {
            j = iter.next();
            if (!visit [j])
                topologicalSort (j, visit, sta);
        }
        sta. push (new Integer (vec) );
    }
    void topologicalSort1()
    {
        Stack <Integer> sta = new Stack <Integer> ();
 
        boolean visit [] = new boolean [Vec];
        for (int i = 0; i < Vec; i++)
            visit [i] = false;
         for (int i = 0; i < Vec; i++)
            if (visit [i] == false)
                topologicalSort(i, visit, sta);
        while (sta. empty() == false)
            System.out.print(sta.pop() + " ");
    }
 
    // Driver code
    public static void main(String args[])
    {
        ConstructingGraph obj1 = new ConstructingGraph (6);
        obj1. addEdge (5, 2);
        obj1. addEdge (5, 0);
        obj1. addEdge (4, 0);
        obj1. addEdge (4, 1);
        obj1. addEdge (2, 3);
        obj1. addEdge (3, 1);
 
        System.out.println ( "Topological Sort of the given graph");
        obj1. topologicalSort1 ();
    }
}

Output:

Topological Sort of the given graph
5 4 2 3 1 0

Python code for Topological Sort:

from collections import defaultdict
 
 
class ConstructingGraph:
    def __init__ (self, vert):
        self. gra = defaultdict(list) 
        self. V = vert  
    def adEdg (self, p, q):
        self. gra [p]. append (q)
    def topologicalSort (self, q, visit, sta):
        visit [q] = True
        for i in self. gra [q]:
            if visit [i] == False:
                self. topologicalSort (i, visit, sta)
        sta. append (v)
    def topologicalSort1 (self):
        visit = [False] * self.V
        sta = []
        for i in range(self.V):
            if visit [i] == False:
                self. topologicalSort (i, visit, sta)
        print( sta [::-1]) 
g1 = ConstructingGraph (6)
g1. addEdge (5, 2)
g1. addEdge (5, 0)
g1. addEdge (4, 0)
g1. addEdge (4, 1)
g1. addEdge (2, 3)
g1. addEdge (3, 1)
 
print ("Topological Sort of the given graph")
g.topologicalSort1 ()

Output:

Topological Sort of the given graph
5 4 2 3 1 0

C++ code for Topological Sort:

#include <iostream>
#include <list>
#include <stack>
using namespace std;
class ConstructingGraph 
{
    int Vec;
    list <int> * ad;
    void topologicalSort (int p, bool visit[], stack <int>& Sta);
 
public:
    ConstructingGraph (int Vec);
    void adEdg (int q, int p);
    void topologicalSort1 ();
};
 
Graph :: ConstructingGraph (int Vec)
{
    this -> Vec = Vec;
    ad = new list <int> [Vec];
}
 
void Graph :: adEd (int q, int p)
{
    ad [q]. push_back (p);
}
void Graph :: topologicalSort (int q, bool visit [], stack<int>& Sta)
{
    Visit [q] = true;
    list<int> :: iterator j;
    for (j = ad [q]. begin (); i != ad[q]. end (); ++i)
        if (!visited [*j])
            topologicalSort (*j, visit, Sta);
    Sta. push (v);
}
 
void Graph :: topologicalSort1 ()
{
    stack<int> Sta;
 
    // Mark all the vertices as not visited
    bool* visit = new bool [Vec];
    for (int i = 0; i < Vec; i++)
        visit [i] = false;
 
    // Call the recursive helper function
    // to store Topological
    // Sort starting from all
    // vertices one by one
    for (int i = 0; i < Vec; i++)
        if (visit[i] == false)
            topologicalSort (i, visited, Sta);
 
    // Print contents of stack
    while (Sta. empty () == false) {
        cout << Sta.top() << " ";
        Sta. pop ();
    }
}
 
// Driver Code
int main()
{
    // Create a graph given in the above diagram
    ConstructingGraph G1 (6);
    G1. addEdge (5, 2);
    G1. addEdge (5, 0);
    G1. addEdge (4, 0);
    G1. addEdge (4, 1);
    G1. addEdge (2, 3);
    G1. addEdge (3, 1);
 
    cout <<”Topological Sort of the given "
            "graph \n";
 
    // Function Call
    G1. topologicalSort ();
 
    return 0;
}

Output:

Topological Sort of the given graph
5 4 2 3 1 0

Related Topics

SQL CONSTRAINTS

SQL Constraints specifies the rules/limitations/restrictions for data present in table. SQL Constraints are specified at the time of table creation or after table creation using ALTER command. There are two...

5 minutes read.

SQL Data Manipulation Language

Data Manipulation Language manipulates/make changes in data present in a table. It only affects data/records of table, not on the schema/structure of table. INSERT, UPDATE, DELETE are the commands of DML. INSERT: Stores...

2 minutes read.

Grant Command in SQL

What is DCL (Data Control Language)? Data Control Language (DCL) is a computer programming language with syntax intended to manage access to data kept in databases. It is a part of...

3 minutes read.

SQL Wildcards

SQL WILDCARD CHARACTERS: SQL wild card character is used to substitute zero or more characters of a string. These characters are used with the “LIKE” operator. Wild Card Characters in SQL: %_[]^- “%” : It is...

3 minutes read.

SQL SubQuery

The Sub-query in the SQL is the inner query placed or positioned inside another query, which is also known is the outer query. The inner query is embedded in the...

6 minutes read.

SQL KEYS

SQL KEYS are single or multiple attributes used to get data from the table according to the requirement or condition. They can also be used to set up relationships amongst...

3 minutes read.

SQL CROSS Join

In this tutorial, we will help you understand the concept of the SQL CROSS Join clause with the few examples. The SQL CROSS Join query is used to join one or...

5 minutes read.

How to use the BETWEEN operator in SQL

In this entire SQL article, we will understand and learn about the BETWEEN operator concept and how to use it in SQL. What is the BETWEEN operator in SQL? The Between operator...

4 minutes read.

SQL Auto Increment

As we all know, In SQL for unique identification, we assign a column with the primary key. But in some tables, we find difficult to differentiate a column as a...

5 minutes read.

SQL Injection

SQL injection is a technique, this may destroy the database. It is one type of hacking technique. SQL IN WEB PAGES: Injection occurs when we ask for input like an id or...

3 minutes read.

How to use HAVING clause in SQL

In this article, we will learn about the HAVING clause concept and how to use it in SQL. What is the HAVING clause? In Structured Query Language, HAVING Clause used with GROUP...

7 minutes read.

SQL Handling Duplicate

Removing Duplicates using DISTINCT Keyword: By using the DISTINCT keyword in SQL we can remove duplicate characters from tables or databases. A table contains more duplicate values and duplicate values can cause...

4 minutes read.

TCL Commands in SQL

In Structured Query Language, TCL is an abbreviation for Transaction Control Language. A single unit of work in a database is formed after the consecutive execution of commands is known...

6 minutes read.

SQL Comparision Operator

The Comparison Operator compares different data of the Structured Query Language table and checks whether the data are the same, less than, greater than, less than, or greater than equal....

14 minutes read.

SQL Inner Join

In Structured Query Language, the most used join query is the Inner join query. Inner join query retrieves the records from one or more tables with similar data or records. The...

4 minutes read.

SQL Commands

SQL commands are classified into four groups on the basis of their nature. DDL (Data Definition Language) DML (Data Manipulation Language) DCL (Data Control Language) DQL (Data Query Language) NOTE: This...

1 minute read.

SQL FULL JOIN

In this section, we will help you understand the concept of the SQL FULL Join clause with a few examples. The SQL FULL Join query is executed to display the integrated...

3 minutes read.

How to drop a column in SQL?

How to drop a column in SQL Introduction To delete a column from an already created table, one needs to use the ALTER command along with the DROP COLUMN clause. Syntax: ALTER TABLE tablename...

4 minutes read.

SQL NOT Operator

SQL NOT is a Boolean operator used with the WHERE clause. NOT operator shows the records if the expression is false. When we use the NOT operator, we fetch only...

7 minutes read.

How to compare date in SQL

In this section, we will learn about how dates can be compared in SQL. We can compare any random date with another date stored in a column of a table.This comparison...

4 minutes read.