×

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 Arithmetic Operators

This page contains all the information, learn about SQL Arithmetic Operators concept in the SQL table with the help of examples. The Arithmetic Operators is used to perform mathematical calculations on...

5 minutes read.

How to add column in table in SQL ?

How to add column in table in SQL  Introduction To add a column in already created table, one needs to use the ALTER command along with the ADD clause.If in the query,...

7 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 Aliases

SQL Aliases: These are used to give a temporary name for a column or table. These are used to make tables or columns more readable. These are used to rename the table...

2 minutes read.

Trigger in SQL

In this article, we will learn about the concept of trigger in SQL and its implementation with the help of an example. A Trigger in Structured Query Language is a set...

4 minutes read.

Codd’s Rules in SQL

Codd’s Rules Dr. Edgar F. Codd, in 1985, laid down 13 fundamental rules after doing large-scale research on the Relational Model of databases. According to him, every database must follow these...

3 minutes read.

Where vs Having

Difference Between Where and Having The WHERE and HAVING clauses in SQL are used to filter records stored in tables in the databases. The dissimilarities between the WHERE and HAVING clause...

3 minutes read.

SQL Tutorial for Beginners

SQL tutorial provides basic and advanced concepts of Structured Query Language and how you deploy SQL to work with a relational database system. Our SQL tutorial is designed for beginners...

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 Count

Structured Query Language Count() Function is used with Structured Query Language SELECT Statement. SQL Count() function returns the number of items that match the specified criteria in the SELECT statement. Count()...

2 minutes read.

SQL Insert multiple rows

This article will deal with a new insertion method in SQL which inserts multiple rows at a time. Multiple records can be inserted at a time into a specific table with...

4 minutes read.

SQL Data Control Language

Data Control Language decides to whom should (which user) permit access privileges. GRANT and REVOKE are the commands of DCL. GRANT: It gives privileges to user. REVOKE: It takes back privileges from granted...

1 minute read.

How to Add Foreign Key in SQL?

How to Add Foreign Key in SQL Foreign key is an attribute or a set of attributes that references to primary key of same table or another table (relation). Foreign key creation along...

4 minutes read.

DML Commands in SQL

DML is an abbreviation of Data Manipulation Language. Data Manipulation Language commands in Structured Query Language manipulate the data in the database. DML commands are used to retrieve records, add records,...

4 minutes read.

SQL Right Join

The SQL Right Join query displays all the table records and similar records from the left table. The query display zero records if it doesn’t find any similar records. If...

4 minutes read.

SQL Operators

Arithmetic Operators Arithmetic operators are +, -, *, /, % performs addition, subtraction, multiplication, division, modulo respectively. Example:   Select 100+222; Select salary+100 From teacher Where teacher_id=1; Following output screen shows different arithmetic operations. We...

2 minutes read.

DDL Commands in SQL

DDL stands for Data Definition Language. Data Definition Language is a bunch of SQL commands used to create, modify and delete Database schema but not the records or data. Data Definition...

5 minutes read.

WEB SQL

What is Web SQL? In SQL we can create databases, read the data in the databases, insert the records into the databases, and delete the records from the databases. For storing...

4 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.

WHERE Clause vs HAVING Clause

The WHERE Clause and HAVING clause filter the records in the Structured Query Language queries. The main difference between the WHERE clause and the HAVING clause is the WHERE clause...

5 minutes read.